Objective. Students write Bash scripts that use variables, conditionals, loops, and file I/O to perform basic system tasks.
This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.
VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.
Bash (Bourne Again SHell) is the default command-line interpreter on most Linux systems. Security analysts use Bash scripts to automate log parsing, scan networks, check file integrity, and respond to incidents faster than any manual process allows. Because Linux underpins servers, cloud infrastructure, and security appliances, fluency in Bash is a core skill for every cybersecurity role.
A Bash script is a plain-text file containing a sequence of shell commands. The first line is always a shebang that tells the OS which interpreter to use:
```bash
#!/usr/bin/env bash
```
Save the file with a `.sh` extension, make it executable with `chmod +x scriptname.sh`, and run it with `./scriptname.sh`.
Variables store data for reuse. Assign a value with no spaces around the equals sign:
```bash
username="alice"
max_attempts=5
```
Reference a variable by prefixing it with `$`. Use curly braces to avoid ambiguity:
```bash
echo "User: ${username}"
```
Input validation is critical in security scripts. Never trust user-supplied input without checking it. At minimum, verify that a variable is not empty before acting on it:
```bash
if [[ -z "${1}" ]]; then
echo "Error: no argument provided." >&2
exit 1
fi
```
The `-z` flag tests for an empty string. Redirecting errors to `>&2` sends them to standard error, keeping standard output clean for downstream tools.
The `if`/`elif`/`else` construct lets a script make decisions:
```bash
if [[ -f "${filepath}" ]]; then
echo "File exists."
else
echo "File not found."
fi
```
Common file-test operators:
For string comparisons use `==` and `!=` inside double brackets `[[ ]]`. For integers use `-eq`, `-ne`, `-lt`, `-gt`.
Loops let you process collections of data — essential for tasks like pinging a list of hosts or reading every line of a log file.
For loop over a list:
```bash
for ip in 192.168.1.1 192.168.1.2 192.168.1.3; do
ping -c 1 -W 1 "${ip}" > /dev/null 2>&1 && echo "${ip} is up" || echo "${ip} is down"
done
```
While loop reading a file line by line:
```bash
while IFS=: read -r username _ uid gid _ homedir shell; do
echo "User: ${username} Shell: ${shell}"
done < /etc/passwd
```
`IFS=:` sets the field separator to a colon, matching the format of `/etc/passwd`. The `read` command splits each line into named variables; the underscore `_` discards fields we do not need.
Bash provides simple operators for reading, writing, and appending files.
| Operator | Effect |
|----------|--------|
| `>` | Redirect output to a file, overwriting it |
| `>>` | Append output to a file |
| `<` | Read input from a file |
Appending a timestamped log entry is a common security task:
```bash
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
echo "[${timestamp}] Login attempt detected from ${src_ip}" >> /var/log/security_events.log
```
`$(...)` is command substitution — it runs the inner command and places its output into the surrounding expression.
The `stat` command returns detailed file metadata. For a quick permissions check inside a script:
```bash
if [[ -f "${target}" ]]; then
perms=$(stat -c "%a %n" "${target}")
echo "Permissions: ${perms}"
else
echo "${target} does not exist." >&2
exit 1
fi
```
`-c "%a %n"` formats output as octal permissions followed by the filename.
Scripts that loop through IP addresses and send pings — or any network probes — must only target systems you are explicitly authorized to test. Running scans against unauthorized hosts violates the Computer Fraud and Abuse Act (CFAA) and equivalent state laws. Always work inside your designated lab network. Before running any script with elevated privileges, read every line; a one-character mistake in a loop touching `/etc` or `/var` can disrupt a live system. Use your Ubuntu VM for all lab work to protect production environments.
Keep scripts in version control (git) so changes are traceable — a good security practice in itself.
1. Open your Ubuntu VM and launch VS Code.
2. Create a new file with the `.sh` extension and add the shebang line.
3. Write the script using the patterns above.
4. Make it executable: `chmod +x script.sh`
5. Run it: `./script.sh`
6. Compare output to the answer key in the lab guide.
7. Add comments to every control-flow block before peer review.
Answer each question, then check it. Nothing is recorded; this is your own practice.
A free tech program — complimentary, as our commitment to get America working. Help us build VoTechWorks. Tell us what works, what doesn’t, and what you want to learn.