Bash Variables, Conditions and Loops for Security Automation
Student Vocation Cybersecurity Learning Series — Lesson 19 of 30
Welcome to Lesson 19 of the Student Vocation Cybersecurity Learning Series!
In Lesson 18, you learned the fundamentals of Bash scripting, including variables, command substitution, output formatting, exit statuses, and basic conditional statements.
Now you will take the next step by learning how to make scripts more flexible and repeatable.
Imagine that you have five sample files to check. Instead of writing a separate command for each file, you can use a loop. If a script needs to display a different message depending on whether a file exists, you can use a condition. If you need to compare two values, you can use a comparison operator.
These techniques form the foundation of useful automation.
In cybersecurity, they can support authorised file checks, basic reporting, processing sample log data, and routine system administration. The goal of this lesson is to help you understand the programming logic behind those tasks without modifying important system files or interacting with unauthorised systems.
By the end of this lesson, you should be able to:
- Create and use Bash variables reliably.
- Compare strings and numbers.
- Use if, elif, and else.
- Combine conditions with logical operators.
- Write for and while loops.
- Iterate safely over sample files.
- Use quotation marks to handle spaces correctly.
- Check command exit statuses.
- Apply defensive scripting practices.
- Build a small automation script in your own authorised practice environment.
-
Understanding Variables in Bash
A variable stores a value that you can reuse throughout a script.
For example:
student=”Cybersecurity Learner”
course=”Bash Automation”
These statements assign text to two variables.
To display the values, use:
printf ‘Student: %s\n’ “$student”
printf ‘Course: %s\n’ “$course”
Output:
Student: Cybersecurity Learner
Course: Bash Automation
Variable assignment rules
Rule 1: Do not add spaces around the equals sign.
Correct:
course=”Bash Automation”
Incorrect:
course = “Bash Automation”
Bash does not treat the second example as an ordinary variable assignment.
Rule 2: Use $ to access a variable’s value.
For example:
course=”Bash Automation”
echo “$course”
Rule 3: Quote variable expansions when working with text or paths.
For example:
filename=”sample security log.txt”
printf ‘Selected file: %s\n’ “$filename”
Quoting preserves the value as a single argument, even when it contains spaces.
Updating a variable
You can change a variable’s value:
status=”Pending”
status=”Reviewed”
printf ‘Current status: %s\n’ “$status”
The output is:
Current status: Reviewed
The variable contains the most recently assigned value.
Read-only variables
Bash also supports variables that should not be reassigned during normal execution:
readonly course=”Bash Basics”
After declaring this variable read-only, attempting to assign another value to it causes an error.
Read-only variables can help prevent accidental changes within a script, but they do not make the entire script secure.
- Understanding String Comparisons
A string is a sequence of characters, such as a username, filename, label, or status.
Bash lets you compare strings using conditional expressions.
Checking whether two strings are equal
role=”student”
if [[ “$role” == “student” ]]; then
echo “Student role selected.”
else
echo “A different role was selected.”
fi
The == operator checks whether the strings are equal inside the [[ … ]] conditional expression.
Checking whether strings are different
status=”pending”
if [[ “$status” != “approved” ]]; then
echo “The status is not approved.”
fi
The != operator checks whether the two strings differ.
Checking for an empty string
username=””
if [[ -z “$username” ]]; then
echo “The username is empty.”
else
echo “A username has been supplied.”
fi
The -z test is true when the string has zero length.
To check that a string is not empty, use -n:
if [[ -n “$username” ]]; then
echo “A username has been supplied.”
fi
These checks are useful when validating input or determining whether a required value has been provided.
Remember that checking whether a field is non-empty is not the same as verifying that the value is valid or belongs to an authorised user.
-
Comparing Numbers in Bash
Bash provides specific comparison operators for integer values.
Operator |
Meaning |
| -eq | Equal to |
| -ne | Not equal to |
| -gt | Greater than |
| -ge | Greater than or equal to |
| -lt | Less than |
| -le | Less than or equal to |
For example:
attempts=3
if [[ “$attempts” -gt 2 ]]; then
echo “The value is greater than two.”
fi
Output:
The value is greater than two.
Another example:
file_count=5
if [[ “$file_count” -eq 5 ]]; then
echo “Five files were counted.”
fi
Important distinction
String comparisons and numeric comparisons are not interchangeable.
For example, the strings “10” and “2” are not ordered numerically when compared as ordinary text. Use integer comparison operators when comparing valid integer values.
Bash’s standard integer comparisons do not provide general floating-point arithmetic. More advanced numeric calculations require other tools or additional techniques.
For this lesson, use simple whole numbers.
-
Using if, elif, and else
A conditional statement allows a script to make decisions.
The general structure is:
if condition; then
# Commands when the first condition succeeds
elif another_condition; then
# Commands when the second condition succeeds
else
# Commands when no earlier condition succeeds
fi
The elif and else branches are optional. You can use more than one elif branch when several alternatives are needed.
Example: Categorising a numeric value
score=75
if [[ “$score” -ge 80 ]]; then
echo “High score”
elif [[ “$score” -ge 50 ]]; then
echo “Moderate score”
else
echo “Below the selected threshold”
fi
Output:
Moderate score
The first condition checks whether the score is at least 80. Because it is not, Bash checks the elif condition. The score is at least 50, so the second message is printed.
Only the first matching branch is executed.
Example: Checking a sample file
filename=”sample.txt”
if [[ -f “$filename” ]]; then
echo “The sample file exists.”
elif [[ -d “$filename” ]]; then
echo “The path refers to a directory.”
else
echo “The path is not an existing regular file or directory.”
fi
This example distinguishes between an existing regular file, a directory, and a path that matches neither test.
The file and directory tests are useful when scripts need to check expected inputs before processing them.
-
Understanding Logical Operators
Logical operators let you combine conditions.
Inside Bash’s [[ … ]] syntax, two common operators are:
- && — logical AND.
- || — logical OR.
- Logical AND
AND is true only when both conditions are true.
age=20
registered=”yes”
if [[ “$age” -ge 18 && “$registered” == “yes” ]]; then
echo “Both conditions are satisfied.”
else
echo “At least one condition is not satisfied.”
fi
This example uses sample values to demonstrate logic. It is not a real identity or access-control system.
- Logical OR
OR is true when at least one condition is true.
status=”reviewed”
priority=”high”
if [[ “$status” == “reviewed” || “$priority” == “high” ]]; then
echo “At least one condition matches.”
fi
Because the priority is high, the condition succeeds.
- Negating a condition
The exclamation mark can negate a condition:
if [[ ! -f “missing-sample.txt” ]]; then
echo “The sample file does not exist.”
fi
The condition succeeds when the named path is not an existing regular file.
A useful defensive habit
Keep complex conditions readable. If a condition becomes difficult to understand, break it into separate checks or use clearly named variables.
Do not rely on complicated conditions you cannot explain or test.
- Introduction to for Loops
A loop repeats a block of instructions.
A for loop is particularly useful when you have a known list of values to process.
Example: Loop through a list
for topic in Linux Bash Networking Security
do
printf ‘Topic: %s\n’ “$topic”
done
Output:
Topic: Linux
Topic: Bash
Topic: Networking
Topic: Security
During each iteration, the variable topic holds one item from the list.
The loop ends after all four items have been processed.
Why loops are useful
Without a loop, you might write separate output statements for every topic. A loop allows you to write one set of instructions and reuse it for every item.
This is useful when processing:
- A list of sample filenames.
- A set of authorised report categories.
- A collection of known values.
- A list of test cases.
- Sample log entries.
-
Safely Iterating Over Sample Files
Suppose you have several practice files in a dedicated directory. You can use a loop to examine their names without changing their contents.
First, create a directory for the sample data:
mkdir -p ~/bash-practice/sample-files
cd ~/bash-practice/sample-files
Create three harmless text files:
printf ‘Sample entry one\n’ > alpha.txt
printf ‘Sample entry two\n’ > beta.txt
printf ‘Sample entry three\n’ > ‘security notes.txt’
These commands create or overwrite files with the specified names in the current directory. Use this only in your dedicated practice directory, and do not use filenames that contain work you need to preserve.
Now return to the parent practice directory:
cd ~/bash-practice
Create a script named list-samples.sh using a text editor:
nano list-samples.sh
Enter:
#!/usr/bin/env bash
sample_dir=”$HOME/bash-practice/sample-files”
for file in “$sample_dir”/*.txt
do
if [[ -f “$file” ]]; then
printf ‘Found sample file: %s\n’ “$file”
fi
done
Save the script, then run:
bash list-samples.sh
The script should display the paths of the three sample files.
Why the quotation marks matter
Notice the expression:
“$sample_dir”/*.txt
The directory path is quoted so that spaces in the directory name are handled correctly. The wildcard remains outside the quotes so Bash can expand it to matching filenames.
The for loop processes the resulting pathnames, and the -f test confirms that each matched path is a regular file.
A subtle detail about unmatched wildcards
By default, if no file matches a wildcard such as *.txt, Bash may leave the pattern unchanged. In the example above, the -f test prevents that unmatched pattern from being reported as a real file.
More advanced scripts may use options such as nullglob to handle unmatched patterns differently. We will keep the example simple for now.
-
Introduction to while Loops
A while loop repeats its instructions as long as its condition succeeds.
General structure:
while condition
do
# Commands to repeat
done
Example: Counting from one to five
count=1
while [[ “$count” -le 5 ]]
do
printf ‘Count: %s\n’ “$count”
count=$((count + 1))
done
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
The expression:
count=$((count + 1))
uses Bash arithmetic expansion to increase the counter by one.
The loop stops when count becomes 6 because the condition count -le 5 is no longer true.
Avoiding infinite loops
A loop can run indefinitely if its condition never becomes false.
For example, if you forget to increase the counter in the previous example, the condition may remain true forever.
To write safer loops:
- Identify the condition that ends the loop.
- Ensure that the loop can eventually reach that condition.
- Test the loop with a small number of iterations.
- Avoid unnecessary commands that repeatedly consume system resources.
- Use a clear stopping condition when processing input.
- Combining Conditions and Loops
You can place an if statement inside a loop to make a decision for each item.
For example:
for score in 25 55 90
do
if [[ “$score” -ge 80 ]]; then
printf ‘Score %s: High\n’ “$score”
elif [[ “$score” -ge 50 ]]; then
printf ‘Score %s: Moderate\n’ “$score”
else
printf ‘Score %s: Low\n’ “$score”
fi
done
Output:
Score 25: Low
Score 55: Moderate
Score 90: High
This example combines iteration with conditional logic.
In a future cybersecurity exercise, similar logic could categorise sample data based on a clearly defined rule. The important lesson is that a loop processes each item, while a condition determines which action to take for that item.
-
Understanding Exit Statuses in Loops and Conditions
As you learned in Lesson 18, commands return exit statuses.
A status of 0 conventionally indicates success. A non-zero status indicates failure or another reported condition.
You can use an if statement directly with a command:
if test -f “sample-files/alpha.txt”; then
echo “The sample file exists.”
else
echo “The sample file was not found.”
fi
Here, the test command checks the file condition and returns a status that Bash uses to select the appropriate branch.
You can also inspect a status explicitly:
true
status=$?
printf ‘Exit status: %s\n’ “$status”
The status is captured immediately after the command.
Important: $? refers to the status of the most recently completed command. If you run another command first, you may lose the status you intended to inspect.
For many conditions, using a command directly in an if statement is clearer than checking $? manually.
Also remember that the exit status of a script is not a complete guarantee of the correctness or security of every action it attempted.
- Defensive Scripting Practices
Cybersecurity scripts should be predictable, readable, and appropriately limited.
Follow these practices as you learn.
- Work in a dedicated practice directory
Keep exercises and sample files separate from important documents and system files.
- Quote variable expansions
Prefer:
printf ‘%s\n’ “$filename”
This helps preserve spaces and prevents many unintended word-splitting and pathname-expansion problems.
- Validate input
If a script accepts a filename, number, or other value, check that it meets the requirements before using it.
For example, a numeric comparison should receive a valid integer rather than arbitrary text.
A. Check files before processing them
Use tests such as [[ -f “$file” ]] to verify that an expected regular file exists.
B. Avoid unnecessary privileges
Do not use sudo for ordinary practice exercises. Elevated privileges increase the possible impact of a mistake.
C. Understand every command
Never execute a script simply because someone has labelled it as a cybersecurity tool. Review its commands and understand their effects first.
D. Avoid unsafe assumptions
A file’s existence does not prove that its contents are valid. A successful command does not prove that a larger process achieved its objective.
E. Keep loops controlled
Test loops using small sample lists. Make sure while loops have a reachable stopping condition.
F. Separate testing from production work
Practise on sample files and authorised systems before applying automation to important environments.
G. Respect authorisation boundaries
Only automate activities that you are authorised to perform. This lesson focuses on local scripts and sample files, not scanning external systems or changing other people’s systems.
-
Practical Lab: Build a Safe Sample-File Checker
Lab title: Bash Conditions and Loops for File-List Automation
Objective: Create a script that iterates over sample files, counts the files it finds, and displays a simple summary.
Required environment: Your own Linux computer, an authorised WSL environment, or a Linux virtual machine you are permitted to use.
Estimated time: 15–20 minutes.
Lab safety rules
- Work only in ~/bash-practice and its sample-data directory.
- Review the code before running it.
- Do not use administrator privileges.
- Do not point the script at sensitive directories or other people’s files.
- Do not include passwords or secrets in your sample files.
Step 1: Prepare the sample files
If you have not already completed Section 7, create the directory:
mkdir -p ~/bash-practice/sample-files
Create the sample files inside that directory:
printf ‘Sample entry one\n’ > ~/bash-practice/sample-files/alpha.txt
printf ‘Sample entry two\n’ > ~/bash-practice/sample-files/beta.txt
printf ‘Sample entry three\n’ > “$HOME/bash-practice/sample-files/security notes.txt”
These commands overwrite files with the same names if they already exist. Use them only in your dedicated practice directory when those files are safe to replace.
Step 2: Create the checker script
Open the script file:
nano ~/bash-practice/check-samples.sh
Enter the following:
#!/usr/bin/env bash
sample_dir=”$HOME/bash-practice/sample-files”
count=0
if [[ ! -d “$sample_dir” ]]; then
printf ‘Error: sample directory not found.\n’ >&2
exit 1
fi
for file in “$sample_dir”/*.txt
do
if [[ -f “$file” ]]; then
count=$((count + 1))
printf ‘Checked: %s\n’ “$file”
fi
done
printf ‘Total sample files found: %s\n’ “$count”
exit 0
Save the file and exit the editor.
Step 3: Understand the script
Variable assignments
sample_dir=”$HOME/bash-practice/sample-files”
count=0
These store the practice directory path and initialise the counter.
Directory validation
if [[ ! -d “$sample_dir” ]]; then
This checks whether the directory is not an existing directory. If the check succeeds, the script displays an error and exits with a non-zero status.
Looping through sample files
for file in “$sample_dir”/*.txt
This iterates over paths matching the .txt wildcard in the designated sample directory.
Checking and counting
if [[ -f “$file” ]]; then
count=$((count + 1))
fi
The script counts only paths that are existing regular files.
Exit status
exit 0
This explicitly reports success at the end of the script, provided execution reaches that line. In a more advanced script, you would also carefully handle failures that occur during processing.
Step 4: Run the script
Execute:
bash ~/bash-practice/check-samples.sh
You should see the names of the three sample text files and a summary reporting three files.
The order of filenames may vary.
Step 5: Check the result
Immediately after running the script, execute:
echo “$?”
If the script completed normally, the exit status should be 0.
Step 6: Practise changing the data
Create one more sample file:
printf ‘Additional practice entry\n’ > “$HOME/bash-practice/sample-files/gamma.txt”
Run the checker again. The reported count should now be four.
Step 7: Test the missing-directory condition safely
The checker expects its sample directory to exist. You can test its error-handling branch without renaming or deleting any directory by creating a separate copy of the script and changing the sample_dir assignment in that copy to a new path that you know does not exist, such as:
sample_dir=”$HOME/bash-practice/directory-that-does-not-exist”
Run the test copy and observe the error message. It should exit with status 1.
Do not alter the original checker if you want to preserve it for future exercises.
Step 8: Lab review questions
Answer these questions in your notes:
- What is the purpose of the count variable?
- Why does the script check whether the sample directory exists before starting the loop?
- Why is “$file” quoted?
- What happens when another .txt sample file is added?
- What is the difference between exit 0 and exit 1 in this example?
Lab completion criteria
You have completed this lab when you can:
- Use variables to store a path and a counter.
- Write string or numeric comparisons where appropriate.
- Use if and else to handle a condition.
- Iterate over a set of local sample files using a for loop.
- Count matching regular files.
- Interpret the script’s exit status.
- Explain how the script handles a missing sample directory.
- Describe why limiting the script to a dedicated practice directory is a good defensive practice.

