🚧 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 › Web & Software Development › Linux/Bash for Web & Software Development › Lesson 5
TEC-WEB46-06 · Lesson 5 · 18 clock hours · lab

Bash Scripting Fundamentals

Objective. Students will write Bash scripts using variables, conditionals, loops, and functions to automate a defined development task.

⚠ 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 a Bash Script?

A Bash script is a plain-text file containing a sequence of shell commands that the Bash interpreter executes in order. Scripts let you automate repetitive tasks — running tests, packaging files, checking system state before a deployment — so you spend less time typing the same commands and more time writing code. Every script you write for this course should be treated like production code: readable, commented, and tested before use.

The Shebang Line

The very first line of every Bash script must be the shebang:

```bash

#!/usr/bin/env bash

```

This tells the operating system which interpreter to use. Using `/usr/bin/env bash` rather than a hard-coded path like `/bin/bash` makes the script portable across Linux distributions where Bash may live in a different location.

After writing the script, make it executable:

```bash

chmod +x myscript.sh

```

Then run it with `./myscript.sh` or `bash myscript.sh`.

Variables

Variables store values you want to reuse. Assign them with no spaces around the equals sign:

```bash

SOURCE_DIR="/home/student/project"

TIMESTAMP=$(date +%Y%m%d_%H%M%S)

```

The `$(...)` syntax — called command substitution — runs the inner command and captures its output as a string. Reference a variable by prefixing it with `$`. Quoting variables with double quotes (`"$VARIABLE"`) prevents word-splitting errors when the value contains spaces.

Positional Parameters and Arguments

Scripts can accept command-line arguments. Inside the script, `$1` is the first argument, `$2` the second, and so on. `$0` is the script's name itself. `$#` holds the total count of arguments. This lets you write flexible, reusable scripts:

```bash

SOURCE_DIR="$1"

```

Always validate arguments before using them — do not assume the caller provided a sane value.

Conditionals

The `if` statement tests a condition and branches accordingly:

```bash

if [ -d "$SOURCE_DIR" ]; then

echo "Directory found."

else

echo "ERROR: Directory does not exist." >&2

exit 1

fi

```

Common file-test operators:

For command output tests (like checking `git status`), capture the output and compare it as a string, or test the command's exit code directly with `if command; then`.

Send error messages to standard error with `>&2` so they do not pollute standard output.

Exit Codes

Every command returns an exit code: `0` means success; any non-zero value means failure. Your scripts should follow the same convention. Use `exit 0` at the end for success and `exit 1` (or another non-zero value) when a precondition fails. Calling programs — CI/CD pipelines, deployment tools — rely on exit codes to know whether a script succeeded.

Loops

Bash provides `for`, `while`, and `until` loops. A common pattern iterates over a list:

```bash

for FILE in "$SOURCE_DIR"/*.conf; do

echo "Checking $FILE"

done

```

A `while` loop reads lines from a file or runs until a condition changes:

```bash

while IFS= read -r LINE; do

echo "$LINE"

done < input.txt

```

Functions

Functions group related commands under a name, reducing repetition:

```bash

check_port() {

local PORT="$1"

if ss -tuln | grep -q ":${PORT} "; then

echo "ERROR: Port $PORT is already in use." >&2

exit 1

fi

}

check_port 8080

```

Use `local` to keep variables inside the function, preventing accidental interference with the rest of the script.

Checking Git Status and System State

For your `deploy_check.sh` lab, you will test three preconditions:

1. Git working tree is clean — `git status --porcelain` prints nothing when the tree is clean. Capture the output and test whether it is empty.

2. Config file exists — use `-f` to test for a regular file.

3. Port is not in use — `ss -tuln` lists listening TCP and UDP sockets. Pipe its output through `grep` to look for the port number.

Safety and Good Practices

Bash scripts run with the permissions of the user who executes them. A script run as root can modify or delete any file on the system. Follow these rules:

Key terms8

ShebangThe first line of a script (`#!/usr/bin/env bash`) that tells the operating system which interpreter should execute the file.
Positional parameterA variable (`$1`, `$2`, etc.) that holds a command-line argument passed to a script when it is invoked.
Exit codeAn integer returned by a command or script when it finishes; `0` indicates success and any non-zero value indicates failure.
Command substitutionThe `$(...)` syntax that runs a command inside a script and captures its standard output as a string value.
set -euo pipefailA Bash option string that makes scripts exit immediately on errors, treat unset variables as errors, and propagate failures through pipelines.
File-test operatorA conditional expression such as `-f`, `-d`, or `-e` used inside `[ ]` to check properties of a file or directory.
Function (Bash)A named block of Bash commands defined with `name() { ... }` that can be called by name and can accept its own positional parameters.
Standard error (stderr)The output stream (file descriptor 2) used for error and diagnostic messages, separate from standard output, redirected with `>&2`.
In class: Worked example: instructor live-codes a backup script that accepts a source directory argument, checks whether it exists, creates a timestamped tarball in /tmp, and prints a success or error message; students type along and run at each step. · Individual scripting lab: students write a script named 'deploy_check.sh' that verifies three preconditions before a mock deployment (git status is clean, a config file exists, a port is not already in use using 'ss -tuln'); script exits with a descriptive error if any check fails. · Script review session: each student reads another student's script aloud, explains what each section does, and suggests one improvement; improvements are implemented and re-tested.
Materials: Student VMs, Bash reference manual (gnu.org/software/bash/manual), lab instruction sheet, VS Code with Bash IDE extension or vim
Check: Instructor runs deploy_check.sh against three pre-set scenarios (pass, fail on config, fail on port); script must handle all three correctly with clear exit messages — pass requires 3/3 scenarios correct.

Practice check8

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

Linux Operations and Scripting (CompTIA Linux+)
1. Which line must appear at the very beginning of a portable Bash script to specify the interpreter?
Linux Operations and Scripting (CompTIA Linux+)
2. A script contains the line `TIMESTAMP=$(date +%Y%m%d_%H%M%S)`. What does the `$(...)` syntax do?
Linux Operations and Scripting (CompTIA Linux+)
3. Inside `deploy_check.sh`, you want to verify that a file named `app.conf` exists before continuing. Which condition is correct?
Linux Operations and Scripting (CompTIA Linux+)
4. A deployment script finishes successfully. Which exit code should it return by convention?
Linux Operations and Scripting (CompTIA Linux+)
5. You add `set -euo pipefail` near the top of a script. What does the `-u` option specifically do?
Linux Operations and Scripting (CompTIA Linux+)
6. In `deploy_check.sh`, the following code is used to test whether a port is in use: ```bash if ss -tuln | grep -q ":8080 "; then echo "ERROR: Port 8080 is in use." >&2 exit 1 fi ``` Why is the error message redirected with `>&2`?
Linux Operations and Scripting (CompTIA Linux+)
7. A student writes a Bash function like this: ```bash check_git() { local STATUS STATUS=$(git status --porcelain) if [ -n "$STATUS" ]; then echo "ERROR: Working tree is not clean." >&2 exit 1 fi } ``` What does the `-n` test operator check?
Linux Operations and Scripting (CompTIA Linux+)
8. Which of the following best describes the benefit of using `local` when declaring variables inside a Bash function?
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.