🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Cybersecurity › Scripting for Cybersecurity › Lesson 2
TEC-CYBE44-05 · Lesson 2 · 14 clock hours · lab

Bash Fundamentals: Variables, Control Flow, and File Operations

Objective. Students write Bash scripts that use variables, conditionals, loops, and file I/O to perform basic system tasks.

⚠ Pending professional review

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.

What Is Bash and Why Does It Matter in Cybersecurity?

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

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.

Conditionals

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

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.

File Operations

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.

Checking Permissions

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.

Safety and Ethics

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.

Lab Workflow Summary

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.

Key terms8

ShebangThe first line of a Bash script (`#!/usr/bin/env bash`) that tells the operating system which interpreter should execute the file.
VariableA named storage location in a script that holds a value; referenced with a leading `$` sign and optionally enclosed in curly braces.
Input validationChecking that data supplied to a script (from a user, file, or network) meets expected format and range constraints before the script acts on it — a fundamental secure-coding practice.
Conditional (if/elif/else)A control-flow structure that executes different commands depending on whether a tested condition evaluates to true or false.
IFS (Internal Field Separator)A special Bash variable that defines the character(s) used to split input into fields; set to a colon when parsing colon-delimited files such as `/etc/passwd`.
Command substitutionThe `$(...)` syntax that runs a command and replaces itself with that command's standard output, allowing the result to be stored in a variable or embedded in a string.
Redirect operatorA symbol that controls where a command's output goes: `>` overwrites a file, `>>` appends to a file, and `<` reads input from a file.
File-test operatorA flag used inside `[[ ]]` to check properties of a file or directory, such as `-f` (regular file exists), `-d` (directory exists), or `-x` (file is executable).
In class: Guided coding exercise: students follow instructor live-coding of a script that reads /etc/passwd, loops through each line, and prints usernames with their shell, then modify it independently. · Practice set: students write three short scripts — one that checks if a file exists and reports its permissions, one that loops through a list of IP addresses and pings each, and one that appends a timestamped entry to a log file. · Peer review pairs: each student reads a partner's scripts, adds inline comments explaining every major line, and flags any variables that lack input validation.
Materials: Ubuntu VM, Bash reference manual (GNU.org), VS Code editor, course lab guide chapter 2
Check: All three practice scripts execute without errors, produce correct output verified against an answer key, and include comments on every control-flow block; pass mark is 3 of 3 scripts functional with comments present.

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

Security+ — General Security Concepts / Secure Coding
1. A student writes `logfile=/var/log/events.log` and later calls `echo $logfile`. The variable is not enclosed in double quotes. Which risk does this create?
Security+ — General Security Concepts
2. Which shebang line is the most portable way to specify the Bash interpreter for a script intended to run on multiple Linux distributions?
Security+ — Governance, Risk, and Compliance
3. A security analyst writes a Bash script that loops through a list of IP addresses and runs `ping` against each one. Before running the script in a client engagement, the analyst must:
CySA+ — Security Operations
4. In the following code, what does `IFS=:` accomplish? ```bash while IFS=: read -r user _ uid gid _ home shell; do echo "${user} uses ${shell}" done < /etc/passwd ```
CySA+ — Security Operations
5. A script must append a timestamped alert to `/var/log/alerts.log` without overwriting existing entries. Which redirect operator is correct?
Security+ — General Security Concepts / Secure Coding
6. A student wants a script to exit with an error message if the first positional argument (`$1`) is empty. Which code block correctly implements this?
Security+ — General Security Concepts
7. Which command makes `myscript.sh` executable by its owner while leaving group and other permissions unchanged from their current state, using the symbolic mode of chmod?
CySA+ — Vulnerability Management
8. During peer review, a classmate notices that your ping-sweep script stores user-supplied target IP addresses directly in a variable and passes them to the shell without any checking. Which threat does this create?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.