9.2 Bash Shell Scripting: Variables, Expansion, Conditionals, Loops & Functions

Key Takeaways

  • Direct invocation, an explicit interpreter, a sourced script and a parenthesized command list use different execution environments.

  • Use quoted positional and parameter expansions. The colon in the default operators makes an empty value eligible for fallback.

  • Choose Bash or POSIX test syntax deliberately. Validate arithmetic inputs, and account for symlink handling in file tests.

  • Capture the foreground status and PIPESTATUS promptly. Pipefail determines pipeline status, and errexit has context-dependent exceptions.

  • Give functions a clear status and output contract. Treat grep’s no-match return separately from errors.

Last updated: November 2026

Bash Scripting for Linux Administration

A Bash script is a sequence of commands with a defined input, output and exit-status contract. Decide what an absent argument, an empty result and an operational failure mean before wiring the script into a timer or pipeline.

Interpreter and process boundaries

On Linux, a directly executed executable script can declare its interpreter on the first line with a shebang. #!/bin/bash selects that path. #!/usr/bin/env bash finds Bash using the process’s PATH. Confirm that the interpreter exists and that the invoking environment is trusted. Direct execution also depends on path access, execute bits and mount policy.

InvocationEnvironment
./report.shWith an executable file and valid shebang, Linux invokes the requested interpreter in the process executing the script. From an interactive shell, ordinary invocation typically uses a separate process.
bash report.shStarts Bash and reads the named script. Execute permission on the script is unnecessary for this invocation.
source report.sh or . ./report.shExecutes in the current shell. Assignments, functions, option changes and directory changes can persist.
( cd /var/log && pwd )Parentheses create a subshell environment. The directory change stays inside it.

Assignments, arguments and expansion

Assign with name=value and avoid spaces around the assignment operator. export name puts a shell variable in the environment of subsequently launched commands. Children inherit an exported value as part of their execution environment. Use unset name to remove the variable and unset -f report to remove a function. A function can use local name for a variable that is scoped to its call, including nested calls under Bash's dynamic scoping.

Use set -- first "second item" to replace positional arguments. $# is their count, $1 is the first, ${10} is the tenth, and shift removes the first positional argument by default. Use "$@" to preserve one word per argument, including empty arguments. "$*" joins them using the first character of IFS, a space when unset, or no separator when empty. $0 gives the shell or script invocation name. $! identifies the most recent background job’s process, and $$ expands to the invoking shell’s PID even in a parenthesized subshell. Use a utility such as mktemp for a private temporary pathname.

Aliases expand shell words during parsing. alias ll='ls -l' defines an interactive shorthand and unalias ll removes it. Noninteractive Bash usually leaves alias expansion off; define a function for script logic with arguments. set also controls shell options.

ExpansionResult or effect
${name}Expands the variable value. Use braces to delimit the name before adjacent text.
${name:-default}Uses the fallback on unset or null input. Leaves the variable unchanged.
${name-default}Uses the fallback only when unset.
${name:=default}Assigns and uses the fallback when unset or null.
${name:?message}Reports an error when unset or null. A noninteractive shell exits.
${name:+alternate}Uses the alternate only when set and nonempty.
${#name}, ${name:0:3}String length and the first three characters.
${path##*/}, ${path%/*}Removes the longest matching prefix or shortest matching suffix respectively. For /opt/backups/database.sql these give database.sql and /opt/backups. Handle paths without a slash separately when extracting a directory.
${name//pattern/replacement}Replaces every occurrence matching the shell pattern.

Quote ordinary substitutions such as "$path" when an argument must stay intact. Unquoted expansions can undergo field splitting and globbing. IFS controls Bash word splitting and field splitting for read. For example, IFS=: read -r login password uid rest reads colon-separated fields. An output separator can come from a format such as printf '%s,%s\n' "$login" "$uid", or from OFS in Awk. OFS has no special meaning to Bash.

Command substitution $(command) captures stdout with trailing newlines removed. The older backtick syntax does this too, but nesting has different escaping rules. Use value=$(command) and check the assignment status. In a function, declare local value separately because local value=$(command) can hide the substitution’s failure status. $((expression)) performs integer arithmetic. Validate numeric input before passing it to Bash arithmetic.

Conditions, comparisons and loops

Use if command; then ...; else ...; fi to branch on a command’s status. case "${1:-}" in ... esac matches patterns and can handle an empty or missing argument. Use for item in "$@"; do ...; done to process each argument, while test; do ...; done while a condition succeeds, or until test; do ...; done while it fails. Bound retries and report exhausted attempts. break leaves the loop, while continue advances to the next iteration.

Test in BashExample and meaning
Numeric equality/ordering-eq, -ne, -lt, -le, -gt and -ge compare integers, for example [[ $count -ge 10 ]] with validated input.
String equality[[ $role == "web" ]] matches a literal. Bash also accepts = here; POSIX [ "$role" = web ] uses =. An unquoted right operand in [[ ]] can be a shell pattern, including with !=.
String ordering[[ $a < $b ]] and [[ $a > $b ]] compare lexically in the current locale. Test equality separately to include it. Bash [[ ]] has no <= or >= string operators. For numeric ordering, (( a <= b )) is arithmetic syntax.
Regular expressionre='^web[0-9]+$' then [[ $host =~ $re ]] uses an extended regular expression. Quoting the variable on the right makes its contents literal. Anchors constrain the whole value.
File tests-d tests for a directory, -f for a regular file, and -s for nonzero size. Most file tests, including these, follow symbolic links; -L tests for a link itself.
Strings and negation-n tests for nonempty input, -z for empty input, and ! inverts a test.

[ is a command, so preserve arguments with quoting and separate tests with shell && or ||. [[ ]] is Bash syntax and suppresses ordinary word splitting and filename expansion for its words. It still applies the comparison rules in the table. For line input, use redirection to keep the loop in the current shell:

while IFS= read -r line || [[ -n $line ]]; do
    printf '<%s>\n' "$line"
done < ./lab-input.txt

An empty IFS preserves surrounding whitespace, -r preserves backslashes, and the final condition handles nonempty input without a trailing newline. A failed read can also indicate an input error. In production, choose a reader and error-reporting strategy that match the data source and integrity requirements.

Exit status and pipeline evidence

A function reports a status with return, and can emit data on stdout. Without an explicit return, its status is the last command’s status. Use stderr for diagnostics and capture $? before another command replaces it. Status zero usually means success. A nonzero value has command-specific meaning: GNU grep uses 1 for no selected lines and normally 2 for an error. Bash uses 126 when a command is found but cannot be executed, 127 for command not found and 128 plus the signal number when it reports signal termination. The same numeric value can be an ordinary exit status.

By default Bash reports the last command’s status for a foreground pipeline. set -o pipefail makes it the rightmost nonzero status, or zero when all succeed. The following fixture intentionally makes the left side fail. Capture the aggregate and individual statuses in one assignment before another command overwrites them:

set -o pipefail
false | true
snapshot=("$?" "${PIPESTATUS[@]}")
printf 'pipeline=%s left=%s right=%s\n' "${snapshot[@]}"

This prints pipeline=1 left=1 right=0. In a script with set -e, an unguarded failing foreground pipeline can exit before the assignment. Put an expected failure in an explicit test and capture the statuses immediately in the matching branch.

set -euo pipefail enables three separate options. -e has exceptions for if or loop conditions, nonfinal commands in &&/|| lists, nonfinal pipeline components and inverted tests. A function called as a condition can inherit the context where errexit is ignored. Ordinary Bash command substitution clears -e unless POSIX mode or inherit_errexit keeps it. -u treats many unset expansions as errors, with defined exceptions including "$@" and default-value expansions. Check expected statuses explicitly. Use set -x only when tracing expanded arguments will not expose secrets.

Worked example — report serious messages from a lab log

This script takes exactly one non-option log pathname. It treats an empty match set as success and emits an error when GNU grep cannot read the file. The function separates its local variables from the caller’s.

#!/usr/bin/env bash
set -u

report_critical_count() {
    local log=$1
    local count status

    if count=$(grep -Fc -- 'CRITICAL' "$log"); then
        printf 'critical=%s\n' "$count"
    else
        status=$?
        case $status in
            1) printf 'critical=0\n' ;;
            *)
                printf 'Cannot read report input %s (grep status %s)\n' "$log" "$status" >&2
                return 2
                ;;
        esac
    fi
}

if [[ $# -ne 1 || $1 == - ]]; then
    printf 'Usage: %s LOGFILE\n' "$0" >&2
    exit 64
fi

report_critical_count "$1"

For a fixture with two matching lines, expect critical=2 and status 0. For an existing file with no matches, expect critical=0 and status 0. For a missing path, expect a diagnostic and status 2. This check counts matching lines, so two occurrences on one line contribute one. Similarly, a backup script must check its archive operation and verify usable recovery before treating the archive as recoverable.

Test Your Knowledge

A Bash script evaluates "${TARGET_DIR:-/var/backups}". How does this expansion affect an unset or empty TARGET_DIR?

A

It assigns /var/backups to TARGET_DIR.

B

It deletes the contents of /var/backups.

C

It yields /var/backups without changing TARGET_DIR.

D

It exits because the expansion references a missing variable.

Test Your Knowledge

In a Bash script, set -euo pipefail is in effect. A foreground pipeline runs as an unguarded top-level command outside any conditional, inversion or AND/OR list. GNU grep fails with status 2 because its input file is missing, and both later stages succeed. What happens after the pipeline completes?

A

The pipeline status is zero because the last stage succeeds.

B

Bash asks whether to ignore the error.

C

Bash converts grep status 2 into the no-matches status.

D

The pipeline has status 2 and Bash exits before the following command.

Test Your Knowledge

CONF names a stable lab path and you want to test the object it resolves to. Which Bash test succeeds only if the target is a nonempty regular file?

A

[[ -d "$CONF" && -r "$CONF" ]]

B

[[ -f "$CONF" && -s "$CONF" ]]

C

[[ -e "$CONF" || -z "$CONF" ]]

D

test -L "$CONF" && test -x "$CONF"

Sections you finish are checked off in the contents.