Writing shell commands directly in the terminal works for one-off tasks, but repeatable automation requires turning those commands into reliable scripts. Without knowing how the kernel reads a script file, how permissions work, and how separate processes differ from the current shell, even a three-line file can fail silently or run under the wrong interpreter.

The Anatomy of a Script

A Bash script is a plain text file containing a sequence of commands. When executed directly, the operating system kernel needs to know which interpreter must parse those commands. This is communicated on the first line using a character sequence known as the shebang: #!.

Following the shebang is the absolute path to the interpreter binary.

bash
#!/usr/bin/env bash

# Print a status message to the terminal
printf '%s\n' 'System initialized.'

Save this file as init.sh. The first line tells the kernel to run /usr/bin/env with bash as an argument. The second line is a comment, which begins with # and extends to the end of the line. The shell ignores comments entirely. The third line runs the built-in printf command.

The Two Shebang Approaches

You will see two common ways to declare the Bash interpreter:

  1. Hardcoded absolute path:
bash
#!/bin/bash
  1. Environment resolution:
bash
#!/usr/bin/env bash

The difference comes down to portability across Unix-like systems. On standard Linux distributions, /bin/bash is almost universally present. On FreeBSD, OpenBSD, or macOS with modern Homebrew-installed Bash versions, Bash may reside in /usr/local/bin/bash or /opt/homebrew/bin/bash.

Using #!/usr/bin/env bash tells the operating system to consult the current PATH variable and use whichever bash executable appears first.

Use #!/usr/bin/env bash when writing scripts that need to run across multiple operating systems or when you rely on a newer Bash version installed in a non-standard directory.

Use #!/bin/bash in locked-down production environments or container images where security policies require deterministic binary paths, or where security hardening strips the env binary. Note that on minimal distributions like standard Alpine Linux, Bash is not installed by default and /bin/bash does not exist until the bash package is explicitly installed.

Permissions and Execution Methods

Creating a file does not grant permission to run it as a program. Modern filesystems track read (r), write (w), and execute (x) permissions for the file owner, group, and others.

Inspect a newly created file:

bash
touch run.sh
ls -l run.sh

The file lacks execute permissions. Attempting to run it directly fails:

bash
./run.sh
text
bash: ./run.sh: Permission denied

To run the file directly as an executable, grant execute permissions using chmod:

bash
chmod +x run.sh

This changes the permission flags to include execute mode (x). Now the kernel can invoke the interpreter specified in the shebang directly via ./run.sh.

Three Ways to Execute a Script

There are three ways to execute a Bash script. Each handles the execution environment differently.

Method 1: Direct Execution (`./script.sh`)

bash
./script.sh

This requires the execute bit (chmod +x). The operating system reads the shebang line, spawns a new process running that interpreter, executes the commands, and returns control to the parent shell.

Any environment variables changed or created inside script.sh disappear when the script finishes. The parent shell environment remains untouched.

Method 2: Interpreter Invocation (`bash script.sh`)

bash
bash script.sh

This explicitly launches the bash binary and passes the file as an argument.

Because you invoke the binary directly, the file does not require the execute bit; read permission is sufficient. Furthermore, the kernel does not process the shebang line to select the binary because the interpreter is already running and parsing the file.

Use this method when running scripts in environments where you cannot modify file permissions (such as certain restricted mounted volumes), or when you want to force a script to run under Bash regardless of what shebang it contains.

Method 3: Sourcing (`source script.sh` or `. script.sh`)

bash
source script.sh
# Or the POSIX-compliant dot operator:
. script.sh

Sourcing does not create a new process. Instead, the current shell reads and runs every line of script.sh within its own process space.

Any variables set, functions defined, or directory changes (cd) made inside the script will persist in your active terminal session after the script finishes.

Use this method strictly for configuration loaders, environment files, or library scripts containing functions you want available in your current session.

Comparison Summary

Execution Style Needs Execute Bit Creates New Process Modifies Calling Shell
./script.sh Yes Yes No
bash script.sh No (read only) Yes No
source script.sh No (read only) No Yes

Pick direct execution (./script.sh) as your default for all standalone automation tasks.

Edge Cases and Pitfalls

Pitfall 1: Windows CRLF Line Endings

If a script is edited on Windows or checked out through Git with improper line-ending translation, line endings become CRLF (\r\n) instead of Unix LF (\n).

When Bash encounters a carriage return (\r) at the end of the shebang line:

text
#!/usr/bin/env bash\r

The kernel attempts to find an interpreter named bash\r, which does not exist:

text
/usr/bin/env: 'bash\r': No such file or directory

Or, on lines within the script:

text
bash: ./script.sh: line 2: {{content}}#x27;\r': command not found

To diagnose this issue:

bash
file script.sh

Output for a corrupted file:

text
script.sh: Bourne-Again shell script, ASCII text executable, with CRLF line terminators

Fix the file using tr to strip out carriage returns:

bash
tr -d '\r' < script.sh > script_fixed.sh && mv script_fixed.sh script.sh

Pitfall 2: Omitting the Path When Executing Locally

In Unix systems, the current working directory (.) is intentionally absent from the system PATH for security reasons. If you try to run an executable in your current folder without specifying its location:

bash
script.sh

The shell responds:

text
bash: script.sh: command not found

You must explicitly state the relative path (./script.sh) or full path (/home/user/script.sh) so the shell knows where to find the file without searching PATH.

Try It

Create a script named reporter.sh that uses environment-based resolution for Bash, prints the message Status: OK using printf, and prints the current process ID using the special parameter $. Note that in Bash, $ always expands to the process ID of the main shell process, not a subshell.

Make the file executable and run it using direct execution. Verify that its process ID is different from your current shell’s process ID.

To inspect your current shell’s process ID:

bash
printf '%s\n' "$"
Solution

Write the script:

bash
#!/usr/bin/env bash

# Print status and the script process PID
printf 'Status: OK\n'
printf 'Script PID: %s\n' "$"

Make it executable:

bash
chmod +x reporter.sh

Execute the script:

bash
./reporter.sh

Because ./reporter.sh executes in a separate process, the printed PID will not match your interactive shell’s PID. If you run source reporter.sh, the printed PID will match your interactive shell.

Scripts must react to dynamic states like missing files, empty inputs, or failed commands, and they must repeat tasks across varying datasets. Without control flow, shell scripts remain brittle lists of sequential commands that break at the first unexpected condition.

Diagnosing Broken Control Flow

Consider a script written to inspect a target directory, process log files if present, or alert the user if the directory is missing.

bash
#!/usr/bin/env bash
set -euo pipefail

target_dir="/tmp/app logs"

if [ -d $target_dir ]; then
    for file in $(ls "$target_dir"); do
        echo "Processing $file"
    done
else
    echo "Directory missing: $target_dir"
fi

Save this as process.sh, make it executable, and run it when /tmp/app logs contains spaces:

text
./process.sh: line 6: [: /tmp/app: unary operator expected

If the directory name contains no spaces and contains server error.log, the output produces unintended splits:

text
Processing server
Processing error.log

The script fails on two fundamental issues: word splitting inside the legacy test command [, and parsing the output of ls in a loop.

In Bash, [ is not syntax; it is an alias for the builtin command test. It evaluates arguments passed to it. When $target_dir expands to an empty value or contains spaces, the shell splits the value into separate tokens before [ executes, resulting in too many or too few arguments.

Parsing ls via command substitution $(ls ...) causes the shell to split output on any whitespace defined in IFS (Internal Field Separator), which includes spaces, tabs, and newlines. The file server error.log becomes two separate tokens: server and error.log.

Conditional Branching: if, test, and [[

The if statement in Bash evaluates the exit status of a command. An exit status of 0 denotes success (true); any non-zero exit status denotes failure (false).

bash
#!/usr/bin/env bash
set -euo pipefail

target="/tmp/app_logs"

if mkdir -p "$target"; then
    echo "Directory ensured: $target"
fi
text
Directory ensured: /tmp/app_logs

Because mkdir -p returns 0 upon creating or confirming the directory, the block executes.

To perform logical checks, string comparisons, and file test operations, use [[ ... ]]. Unlike [ ... ], [[ ... ]] is native Bash syntax, not a regular command. It prevents word splitting and pathname expansion inside the brackets, reducing quoting requirements.

bash
#!/usr/bin/env bash
set -euo pipefail

file_path="/etc/hosts"

if [[ -f "$file_path" && -r "$file_path" ]]; then
    echo "File exists and is readable: $file_path"
elif [[ ! -e "$file_path" ]]; then
    echo "File does not exist: $file_path"
else
    echo "File exists but is not readable: $file_path"
fi
text
File exists and is readable: /etc/hosts

Common conditional operators inside [[ ... ]]:

  • -f "$var": True if the path exists and is a regular file.
  • -d "$var": True if the path exists and is a directory.
  • -z "$var": True if the string length is zero.
  • -n "$var": True if the string length is non-zero.
  • "$a" == "$b": True if strings match. Accepts pattern matching on the right-hand side.
  • "$a" =~ $pattern: True if the string matches the Extended Regular Expression (ERE).

Pattern matching with == allows glob-style verification:

bash
#!/usr/bin/env bash
set -euo pipefail

archive="backup-2026-03-30.tar.gz"

if [[ "$archive" == *.tar.gz ]]; then
    echo "Valid gzip tarball format."
fi
text
Valid gzip tarball format.

When using regular expressions with =~, keep the regex unquoted or store it in a variable. Quoting the regex turns it into a literal string comparison.

bash
#!/usr/bin/env bash
set -euo pipefail

identifier="NODE-8492"

if [[ "$identifier" =~ ^NODE-[0-9]+$ ]]; then
    echo "Pattern matched: $identifier"
else
    echo "Invalid identifier"
fi
text
Pattern matched: NODE-8492

Iterating with for Loops

Never parse ls to iterate over files. Use native Bash pathname expansion (globbing). Globs handle arbitrary characters safely, including spaces, tabs, and newlines.

bash
#!/usr/bin/env bash
set -euo pipefail

# Setup temporary test directory and files
dir=$(mktemp -d)
touch "$dir/access log.txt" "$dir/error log.txt"

# Enable nullglob so unmatched patterns expand to nothing instead of the literal glob
shopt -s nullglob

for file in "$dir"/*.txt; do
    echo "Found: $file"
done

# Cleanup
rm -rf "$dir"

If shopt -s nullglob is omitted and no .txt files exist, $dir/*.txt expands to the literal string "$dir/*.txt", causing downstream errors. Setting nullglob prevents this by expanding to an empty list.

Bash also supports C-style arithmetic loops using (( ... )):

bash
#!/usr/bin/env bash
set -euo pipefail

total=0
for ((i = 1; i <= 5; i++)); do
    ((total += i))
done

echo "Sum: $total"
text
Sum: 15

While and Until Loops

The while loop runs as long as the condition evaluates to exit status 0. The until loop is the inverse: it runs as long as the condition evaluates to a non-zero exit status, stopping the moment the condition succeeds.

A primary use case for while is reading stream inputs line by line using the read builtin.

bash
#!/usr/bin/env bash
set -euo pipefail

data="web01:active:us-east
web02:inactive:us-west
web03:active:eu-central"

while IFS=":" read -r host status region; do
    if [[ "$status" == "active" ]]; then
        echo "Monitoring $host located in $region"
    fi
done <<< "$data"
text
Monitoring web01 located in us-east
Monitoring web03 located in eu-central

Why this combination is mandatory for streams:

  1. IFS=":": Scopes field splitting to the delimiter solely for that read invocation.
  2. -r: Disables backslash escaping, preserving literal paths and characters.
  3. <<< "$data": Uses a “here-string” to feed the input without spawning a subshell pipe.

The until construct works well for polling states, such as waiting for a service or a lock file to disappear:

bash
#!/usr/bin/env bash
set -euo pipefail

attempts=0
max_attempts=3

until [[ $attempts -ge $max_attempts ]]; do
    echo "Attempt: $attempts"
    ((attempts++))
done
text
Attempt: 0
Attempt: 1
Attempt: 2

Pitfalls and Edge Cases

Subshell Variable Loss in Pipelines

Piping data into a loop spawns a subshell for the loop body in standard Bash configurations. Any variables modified inside that loop lose their state outside the pipeline.

bash
#!/usr/bin/env bash
set -euo pipefail

count=0

# Faulty pattern: pipeline creates subshell
printf "a\nb\nc\n" | while read -r line; do
    ((count++))
done

echo "Count is: $count"
text
Count is: 0

To fix this, avoid the pipe by using process substitution or here-strings:

bash
#!/usr/bin/env bash
set -euo pipefail

count=0

while read -r line; do
    ((count++))
done < <(printf "a\nb\nc\n")

echo "Count is: $count"
text
Count is: 3

Missing Final Lines in Streams

read returns a non-zero exit status when it hits an EOF (End of File). If a file or stream does not terminate with a trailing newline, read consumes the final characters, populates the variables, but exits non-zero, causing while to terminate immediately without processing that line.

bash
#!/usr/bin/env bash
set -euo pipefail

# String missing trailing newline
content=$(printf "alpha\nbeta\ngamma")

# Protect against EOF termination by checking if the variable has contents
while read -r item || [[ -n "$item" ]]; do
    echo "Item: $item"
done <<< "$content"
text
Item: alpha
Item: beta
Item: gamma

The logical OR || [[ -n "$item" ]] ensures the loop body executes for the final chunk of data even though read encountered EOF without a newline.

Arithmetic Evaluation and set -e Aborts

When writing scripts with set -e, the arithmetic command evaluation (( ... )) introduces a subtle gotcha. The exit status of (( expression )) depends on the evaluated value: if the expression evaluates to zero, the return status is 1 (failure). If the expression evaluates to non-zero, the return status is 0 (success).

bash
#!/usr/bin/env bash
set -euo pipefail

counter=0
(( counter++ ))
echo "Counter: $counter"

Running this script results in immediate termination before printing:

text
# Script exits silently with code 1 at line 5

Because counter++ is a post-increment operator, the expression yields the original value (0) before incrementing. Under set -e, Bash treats exit status 1 as a fatal failure and terminates execution.

To safely manipulate integers under set -e:

  • Use pre-increment (( ++counter )), which yields 1 if starting from 0.
  • Assign arithmetic results directly: counter=$((counter + 1)).
  • Use the addition assignment operator: (( counter += 1 )).

Worked Example: Rotating Log Files by Size

Here is a practical task demonstrating conditional tests, file globbing, and stream iteration. The goal is to inspect a directory of .log files, archive any file exceeding a size limit (100 bytes for demonstration purposes), and log each action with a timestamp.

bash
#!/usr/bin/env bash
set -euo pipefail

log_dir=$(mktemp -d)
max_bytes=100

# Populate simulated logs with varying sizes
printf "%080d\n" 1 > "$log_dir/auth.log"          # 81 bytes (below limit)
printf "%0150d\n" 2 > "$log_dir/app errors.log"   # 151 bytes (above limit, space in name)
printf "%0200d\n" 3 > "$log_dir/access.log"       # 201 bytes (above limit)
touch "$log_dir/empty.log"                        # 0 bytes

archive_dir="$log_dir/archives"
mkdir -p "$archive_dir"

shopt -s nullglob

for logfile in "$log_dir"/*.log; do
    # Skip if not a regular file
    if [[ ! -f "$logfile" ]]; then
        continue
    fi

    # Read file size in bytes
    size=$(wc -c < "$logfile")

    # Clean whitespace from wc output
    size="${size//[[:space:]]/}"

    filename=$(basename "$logfile")

    if (( size > max_bytes )); then
        timestamp=$(date +"%Y%m%d%H%M%S")
        target_archive="$archive_dir/${filename}.${timestamp}.bak"
        
        mv "$logfile" "$target_archive"
        echo "ARCHIVED: $filename (size: ${size}B) -> $(basename "$target_archive")"
    else
        echo "KEPT: $filename (size: ${size}B)"
    fi
done

# Clean up temporary test files
rm -rf "$log_dir"

Output:

text
ARCHIVED: access.log (size: 201B) -> access.log.20260330120000.bak
ARCHIVED: app errors.log (size: 151B) -> app errors.log.20260330120000.bak
KEPT: auth.log (size: 81B)
KEPT: empty.log (size: 0B)

In this implementation:

  1. shopt -s nullglob prevents the loop from attempting to process "$log_dir/*.log" if no matching files exist.
  2. Globbing safely preserves the filename with spaces (app errors.log).
  3. wc -c < "$logfile" reads input via redirection rather than passing the path as an argument, keeping path strings out of standard output.
  4. (( size > max_bytes )) performs direct integer evaluation without relying on external utilities like [ "$size" -gt "$max_bytes" ].

Try It

Write a script that processes a list of simulated server records. Each record is formatted as server_name,load_average.

Requirements:

  1. Parse each record using a while loop fed by a here-string.
  2. If load_average is an empty string, print an error stating Skipping invalid record for <server_name>.
  3. If load_average is greater than or equal to 5, print CRITICAL: <server_name> load is <load_average>.
  4. Otherwise, print OK: <server_name> load is <load_average>.

Records to parse:

text
srv-app01,2
srv-app02,7
srv-app03,
srv-db01,5
Solution
bash
#!/usr/bin/env bash
set -euo pipefail

records="srv-app01,2
srv-app02,7
srv-app03,
srv-db01,5"

while IFS="," read -r server load || [[ -n "$server" ]]; do
    if [[ -z "$load" ]]; then
        echo "Skipping invalid record for $server"
    elif (( load >= 5 )); then
        echo "CRITICAL: $server load is $load"
    else
        echo "OK: $server load is $load"
    fi
done <<< "$records"

Expected output:

text
OK: srv-app01 load is 2
CRITICAL: srv-app02 load is 7
Skipping invalid record for srv-app03
CRITICAL: srv-db01 load is 5

Scripts that rely on top-level execution become unmaintainable as soon as state changes in one section silently break logic dozens of lines later. Without structured encapsulation, every variable declared in Bash exists in a shared global space, and execution flow becomes difficult to track or test in isolation.

The Naive Approach: Unscoped Sequences

Consider a deployment script that validates user input, prepares a temporary workspace, and logs progress. A common first draft keeps everything in a flat, linear file.

bash
#!/usr/bin/env bash
set -euo pipefail

target_dir="/tmp/app_deploy"
status="pending"

# Validate input
if [[ -z "${1:-}" ]]; then
    status="error"
    echo "Validation failed: target environment missing"
fi

# Prepare directory
if [[ "${status}" != "error" ]]; then
    dir="${target_dir}/build"
    echo "Creating directory: ${dir}"
    status="success"
fi

# Final report
echo "Deployment status: ${status}"

Run this script without arguments:

text
Validation failed: target environment missing
Deployment status: error

At first glance, this works. The problems emerge as the script grows:

  1. Global state pollution: Variables like status, dir, and target_dir remain in the environment for the lifetime of the shell process. If another section reuses status or dir assuming they are empty, unexpected branches execute.
  2. Lack of single-purpose control: Testing whether the validation step works requires executing or commenting out the directory creation code.
  3. No exit status contract: The script relies on tracking a manual string (status="error") instead of communicating failure through standard Linux exit codes.

Idiomatic Functions: Anatomy and Scoping

Bash functions act like internal commands. They take positional arguments ($1, $2, $@), run in the current shell process unless invoked inside a subshell, and exit with an integer status code from 0 to 255.

The standard POSIX and modern Bash declaration syntax is:

bash
function_name() {
    # implementation
}

Avoid the function function_name() syntax. It is redundant and non-standard across different shell implementations.

Variable Isolation with local

By default, every variable assigned inside a function is global. You must explicitly scope variables to the function body using the local builtin.

Here is what happens when you omit local:

bash
#!/usr/bin/env bash
set -euo pipefail

compute_path() {
    path="/etc/app"
}

path="/home/user"
compute_path
echo "Path is now: ${path}"
text
Path is now: /etc/app

The function silently overwrote the caller’s variable. To isolate variables to the current function and its descendants in the call stack, declare them with local:

bash
#!/usr/bin/env bash
set -euo pipefail

compute_path() {
    local path="/etc/app"
    echo "Inside compute_path: ${path}"
}

path="/home/user"
compute_path
echo "In caller scope: ${path}"
text
Inside compute_path: /etc/app
In caller scope: /home/user

Bash uses dynamic scoping, not lexical scoping. A variable declared local in func_a is visible to func_b if func_a calls func_b. It is destroyed only when func_a returns. Keep your functions pure by declaring local variables in every function that needs them, rather than relying on inherited variables from parent functions.

Return Codes vs. Captured Output

Bash does not return objects, strings, or numbers from functions using a return keyword the way Python, Go, or JavaScript do.

  • return N: Immediately exits the function and sets $? to the integer N (0 to 255). It conveys status (0 for success, non-zero for failure).
  • Standard output (echo, printf): Conveys data back to the caller through command substitution.

Mixing up these two mechanisms is the most common design bug in shell scripting.

Returning Status Codes

Use return strictly for control flow and boolean-style outcomes:

bash
#!/usr/bin/env bash
set -euo pipefail

is_port_valid() {
    local port="${1:-}"

    if [[ -z "${port}" ]]; then
        return 2
    fi

    if [[ "${port}" -ge 1024 && "${port}" -le 65535 ]]; then
        return 0
    fi

    return 1
}

check_service() {
    local service_port="${1}"
    local err

    if is_port_valid "${service_port}"; then
        echo "Port ${service_port} is allowed."
    else
        err=$?
        echo "Port ${service_port} rejected with exit code ${err}."
    fi
}

check_service 8080
check_service 80
check_service ""
text
Port 8080 is allowed.
Port 80 rejected with exit code 1.
Port  rejected with exit code 2.

The if is_port_valid "${service_port}"; then statement evaluates the return code of the function directly. No string comparison like [[ $res == "true" ]] is required.

Returning Data via Standard Output

When a function needs to generate a value, print it to standard output, then capture it in the caller using $():

bash
#!/usr/bin/env bash
set -euo pipefail

format_slug() {
    local raw_title="${1}"
    local sanitized

    sanitized="$(echo "${raw_title}" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')"
    printf '%s' "${sanitized}"
}

main() {
    local project_title="Production Web Worker"
    local slug

    slug="$(format_slug "${project_title}")"
    echo "Normalized: ${slug}"
}

main
text
Normalized: production-web-worker

Using printf '%s' prevents trailing newlines from causing unintended whitespace issues in callers.

Pitfalls and Edge Cases

Pitfall 1: Masking Return Codes with local

Declaring a local variable and assigning the output of a command substitution on the same line disables set -e failure detection.

bash
# BROKEN PATTERN
get_config() {
    local config="$(failing_command)"
    echo "${config}"
}

The local builtin is itself a command that returns an exit code of 0 if the variable was created successfully, regardless of what happened inside $(). This hides failures from set -e.

The fix is to separate declaration and assignment:

bash
# IDIOMATIC FIX
get_config() {
    local config
    config="$(failing_command)"
    echo "${config}"
}

Here, if failing_command terminates with a non-zero exit status, the assignment line fails immediately under set -e.

Pitfall 2: Accidental Subshell Overhead

Capturing command output with $(function_name) forces Bash to fork a new process. If you invoke helper functions thousands of times in a loop to transform strings, execution slows down noticeably.

If you only need to determine success or failure, use return and read $?. Avoid printing status strings and capturing them with $().

bash
# BAD: Forks a subshell every loop iteration
if [[ "$(validate_record "${record}")" == "valid" ]]; then
    process "${record}"
fi

# GOOD: Runs in-process, checks status directly
if validate_record "${record}"; then
    process "${record}"
fi

Refactoring to a Modular Architecture

A clean Bash script defines functions at the top and delegates top-level execution to a single main entrypoint function, invoked at the bottom of the script. This keeps variables out of the global namespace and simplifies argument parsing.

bash
#!/usr/bin/env bash
set -euo pipefail

log_info() {
    printf '[INFO] %s\n' "$1"
}

log_error() {
    printf '[ERROR] %s\n' "$1" >&2
}

build_backup_path() {
    local base_dir="${1}"
    local app_name="${2}"
    local timestamp="${3}"

    if [[ -z "${base_dir}" || -z "${app_name}" ]]; then
        return 1
    fi

    printf '%s/%s-%s.tar.gz' "${base_dir}" "${app_name}" "${timestamp}"
}

main() {
    local target_app="${1:-}"

    if [[ -z "${target_app}" ]]; then
        log_error "Missing application name argument."
        return 1
    fi

    local backup_file
    backup_file="$(build_backup_path "/var/backups" "${target_app}" "20260330")"

    log_info "Destination set to: ${backup_file}"
}

main "$@"

Run with missing argument:

text
[ERROR] Missing application name argument.

Run with target argument:

text
[INFO] Destination set to: /var/backups/api-worker-20260330.tar.gz

Try it

Write a script containing two functions:

  1. normalize_env(): Takes a raw string input as $1. If the input is dev, stage, or prod, it prints the full name (development, staging, or production) and returns status 0. If the input is anything else, it prints nothing and returns status 1.
  2. main(): Accepts a command line argument, passes it to normalize_env(). If valid, it prints Configured: <full_name>. If invalid, it prints Unknown environment: <input> to standard error and exits with code 1.
Solution
bash
#!/usr/bin/env bash
set -euo pipefail

normalize_env() {
    local env="${1:-}"

    case "${env}" in
        dev)
            printf '%s' "development"
            return 0
            ;;
        stage)
            printf '%s' "staging"
            return 0
            ;;
        prod)
            printf '%s' "production"
            return 0
            ;;
        *)
            return 1
            ;;
    esac
}

main() {
    local input="${1:-}"
    local resolved_env

    if resolved_env="$(normalize_env "${input}")"; then
        printf 'Configured: %s\n' "${resolved_env}"
    else
        printf 'Unknown environment: %s\n' "${input}" >&2
        return 1
    fi
}

main "$@"
  • Functions isolate logic; declaring variables with local prevents state leaks across the script.
  • Use return only for status codes (0 for success, 1 to 255 for errors).
  • Use standard output (printf) and command substitution ($()) to pass strings and computed data back to the caller.
  • Never combine local and command substitution in a single statement when using set -e, as it masks command failures.
  • Route application flow through a dedicated main "$@" entrypoint to keep top-level code clean and contained.

Every process on a Linux system starts with three communication channels: standard input, standard output, and standard error. Managing these channels allows programs to compose cleanly, isolate errors from data, and persist state to disk without changing application code.

The Anatomy of File Descriptors

The operating system tracks open I/O resources via integer indexes called file descriptors (FDs). By convention, every standard Bash process inherits three:

  • 0: Standard Input (stdin)
  • 1: Standard Output (stdout)
  • 2: Standard Error (stderr)

Redirection operators instruct the shell to modify the file descriptor table for a command before that command executes.

bash
# Redirect stdout to a file (overwrite)
echo "Operation completed" > output.log

# Redirect stdout to a file (append)
echo "System rebooted" >> output.log

# Redirect stderr to a file
ls /path/that/does/not/exist 2> error.log

# Discard stderr entirely
ls /path/that/does/not/exist 2> /dev/null

The syntax [FD]> binds a specific descriptor. When the file descriptor number is omitted before >, Bash defaults to descriptor 1.

Combining and Duplicating Streams

Separating normal data from error output is critical when processing data through pipelines. However, you will often need to consolidate streams for unified logging.

Comparing Two Patterns for Merging stdout and stderr

There are two primary ways to redirect both stdout and stderr to the same destination: the traditional duplication operator and the modern shorthand.

Pattern A: Duplicating File Descriptors (`2>&1`)

bash
#!/usr/bin/env bash

# Redirect stdout to combined.log, then duplicate stderr to wherever stdout points
ls /bin/bash /no-such-file > combined.log 2>&1

cat combined.log

Why it works: Order matters strictly here. Bash processes redirections from left to right.

  1. > combined.log opens combined.log for writing and points descriptor 1 to it.
  2. 2>&1 points descriptor 2 to the file currently pointed to by descriptor 1 (combined.log).

If you invert the order (2>&1 > combined.log), descriptor 2 is redirected to where descriptor 1 currently points (your terminal screen), and then descriptor 1 is redirected to the file. As a result, errors will print to your terminal, not the file.

Pattern B: The Modern Shorthand (`&>`)

bash
#!/usr/bin/env bash

# Modern shorthand to redirect both streams
ls /bin/bash /no-such-file &> combined_shorthand.log

cat combined_shorthand.log

Why it works: &> is shorthand syntax supported in Bash. It achieves the exact same result as > file 2>&1 without ordering pitfalls.

When to Pick Which

  • Use &> for scripts targeting modern environments running pure Bash where readability and speed of comprehension matter most.
  • Use > file 2>&1 when writing scripts that must remain portable across POSIX shells like Dash (the default /bin/sh on Ubuntu and Debian), or when constructing complex redirections involving custom descriptors.

Reading Files: Pipelines vs Process Substitution vs File Redirection

Reading data from disk into a loop is one of the most common scripting tasks. The method you choose dictates whether variables modified inside your loop retain their values outside it.

Pattern A: Piped Input (`cat` or command into `while read`)

bash
#!/usr/bin/env bash

count=0

cat << 'EOF' > items.txt
alpha
beta
gamma
EOF

cat items.txt | while IFS= read -r line; do
    echo "Item: ${line}"
    count=$((count + 1))
done

echo "Final count: ${count}"

Expected output:

text
Item: alpha
Item: beta
Item: gamma
Final count: 0

Why it behaves this way: In Bash, each command in a pipeline runs in a separate subshell. The while loop runs inside an isolated subshell environment. When the loop finishes, the subshell terminates, and the $count modifications are lost.

Pattern B: Direct File Redirection into `while read`

bash
#!/usr/bin/env bash

count=0

cat << 'EOF' > items.txt
alpha
beta
gamma
EOF

while IFS= read -r line; do
    echo "Item: ${line}"
    count=$((count + 1))
done < items.txt

echo "Final count: ${count}"

Expected output:

text
Item: alpha
Item: beta
Item: gamma
Final count: 3

Why it works: Feeding the file directly using < items.txt keeps the loop inside the current shell execution environment. No subshell is spawned, so $count retains its value.

Notice the flags used with read:

  • IFS=: Prevents leading and trailing whitespace from being trimmed.
  • -r: Prevents backslashes from acting as escape characters, preserving raw input.

Pattern C: Process Substitution

When the data you need to read is not in a file on disk, but is produced by another command, process substitution allows you to stream command output into a loop without spawning a pipeline subshell.

bash
#!/usr/bin/env bash

total_bytes=0

# Process substitution acts as a temporary file descriptor: <(...)
while IFS= read -r size; do
    total_bytes=$((total_bytes + size))
done < <(find . -maxdepth 1 -type f -exec stat -c %s {} +)

echo "Total bytes read: ${total_bytes}"

Process substitution syntax <(command) runs command, links its output to a named pipe or /dev/fd/N, and passes that descriptor to the loop input <.

When to Pick Which

  • Use Direct Redirection (done < file) when reading static files. It is fast, creates no extra processes, and preserves variable state.
  • Use Process Substitution (done < <(command)) when reading command output while needing to mutate variables in the current shell scope.
  • Use Pipelines (command | while ...) only when processing streaming data where state persistence outside the loop is unnecessary.

Practical Edge Cases and Pitfalls

1. Reading Files Missing a Final Newline

The read utility returns a non-zero exit status when it hits an End-of-File (EOF) marker. If a file does not end with a trailing newline, read reads the final line into the variable, but immediately returns status 1. In a standard while IFS= read -r line construct, the loop terminates before executing the body for that final line.

bash
#!/usr/bin/env bash

# Write file without a trailing newline
printf "first line\nsecond line without newline" > nonewline.txt

# Pitfall: skips the last line
while IFS= read -r line; do
    echo "Read: ${line}"
done < nonewline.txt

Expected output:

text
Read: first line

The fix: Evaluate the variable content in the loop condition alongside read. If read fails due to EOF, the loop continues if the variable is non-empty:

bash
#!/usr/bin/env bash

printf "first line\nsecond line without newline" > nonewline.txt

# Correct: processes final line even without newline
while IFS= read -r line || [[ -n "${line}" ]]; do
    echo "Read: ${line}"
done < nonewline.txt

Expected output:

text
Read: first line
Read: second line without newline

2. The Truncate-Before-Read Race Condition

A common mistake when trying to update a file in place is using the same file for input and output:

bash
# DANGEROUS: Wipes the file completely before reading it
grep "pattern" data.txt > data.txt

Redirections are set up by the shell before the command executes. The shell opens data.txt with the O_TRUNC flag, emptying it to zero bytes instantly. When grep starts, it reads an empty file.

The fix: Use a temporary file and atomic move, or a tool designed for in-place modifications:

bash
grep "pattern" data.txt > data.txt.tmp && mv data.txt.tmp data.txt

Try It

Write a script that processes an input file containing a list of IP addresses (one per line) and validates each format.

Requirements:

  1. Valid IP lines must be written to valid_ips.txt.
  2. Invalid IP lines must be written to invalid_ips.txt.
  3. Total valid and total invalid counts must be printed to the terminal after processing completes.
  4. Use variable state preservation (no subshell losses).

Assume an IP is valid if it contains four non-empty dot-separated segments made only of digits (a basic regex check is sufficient).

Solution
bash
#!/usr/bin/env bash

# Setup input data
cat << 'EOF' > ip_list.txt
192.168.1.1
10.0.0.256
bad_entry
127.0.0.1
172.16.0.5
EOF

# Clear or initialize destination files
> valid_ips.txt
> invalid_ips.txt

valid_count=0
invalid_count=0

# Basic IPv4 numerical pattern (0-9 digits across four octets)
pattern='^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+{{content}}#x27;

while IFS= read -r line || [[ -n "${line}" ]]; do
    if [[ "${line}" =~ ${pattern} ]]; then
        echo "${line}" >> valid_ips.txt
        valid_count=$((valid_count + 1))
    else
        echo "${line}" >> invalid_ips.txt
        invalid_count=$((invalid_count + 1))
    fi
done < ip_list.txt

echo "Processing complete."
echo "Valid IPs: ${valid_count}"
echo "Invalid IPs: ${invalid_count}"

Bash scripts default to running past errors, silently substituting empty strings for unset variables, and swallowing failures inside pipelines. This behavior turns small typos or missing files into cascading failures that can corrupt state or delete the wrong directory.

The Goal: A Safe Artifact Deployment Script

To master error handling and debugging, you will build a script that stages, validates, and cleans up deployment bundles. The script must halt immediately when commands fail, guard against missing variables, handle failures within pipelines, cleanly remove temporary directories on exit, and supply trace logs when troubleshooting.

Stage 1: Strict Execution Mode with set -euo pipefail

By default, Bash treats a non-zero exit status as a mere suggestion. It prints an error to standard error and continues to the next line.

Here is the baseline script:

bash
#!/usr/bin/env bash
set -euo pipefail

TARGET_DIR="./build"
RELEASE_ARCHIVE="app-v1.tar.gz"

echo "Creating staging directory..."
mkdir -p "${TARGET_DIR}"

echo "Simulating archive unpack..."
# If this fails, set -e stops execution immediately
tar -xzf "${RELEASE_ARCHIVE}" -C "${TARGET_DIR}"

echo "Deployment complete."

If app-v1.tar.gz does not exist, run the script:

text
Creating staging directory...
Simulating archive unpack...
tar (child): app-v1.tar.gz: Cannot open: No such file or directory
tar (child): Error is not recoverable: exiting now
tar: Child returned status 2
tar: Error exit delayed from previous errors

The script halts. The string “Deployment complete.” never prints.

The configuration set -euo pipefail combines three distinct shell flags:

  • -e (errexit): Causes the shell to exit immediately if any command exits with a non-zero status, unless that command is part of an explicit test such as an if condition or a while loop.
  • -u (nounset): Treats referencing an unset variable as an error, immediately exiting the script. In standard Bash, referencing $UNSET_VAR expands silently to an empty string. If you execute rm -rf "${TARGET_DIR}/${SUBDIR}" and SUBDIR was mistyped, standard Bash runs rm -rf "${TARGET_DIR}/". With -u, the shell aborts before running the destructive command.
  • -o pipefail: By default, the return code of a pipeline is the return code of the last command in the sequence. For example, failing_cmd | grep "pattern" returns 0 if grep finds a match or if grep itself succeeds on empty input, concealing the failure of failing_cmd. Setting pipefail means the pipeline returns the exit status of the last command that returned a non-zero status, or zero if all commands succeeded.

Stage 2: Deterministic Cleanup with the EXIT Trap

Stopping early leaves side effects behind. If your script creates temporary scratch space or lockfiles, an unexpected exit via set -e leaves those files on disk.

You solve this with the trap built-in, which binds arbitrary commands to shell signals. The pseudo-signal EXIT fires whenever the shell process terminates, regardless of whether it ran to completion, hit an error under set -e, or received an exit signal.

bash
#!/usr/bin/env bash
set -euo pipefail

# Create a secure temporary directory
WORK_DIR=$(mktemp -d)

# Register cleanup to trigger on script exit
cleanup() {
    local exit_code=$?
    echo "Running cleanup for: ${WORK_DIR}"
    rm -rf "${WORK_DIR}"
    exit "${exit_code}"
}
trap cleanup EXIT

echo "Staging files in ${WORK_DIR}..."
touch "${WORK_DIR}/manifest.txt"

# Trigger an intentional error to test the trap
echo "Reading configuration..."
grep "release_version" "${WORK_DIR}/manifest.txt"

echo "This line will not run."

Notice that grep returned exit code 1 because the search string was not found. Under set -e, this triggered an immediate script termination, yet cleanup ran automatically, removing the temporary directory.

Capturing $? inside the trap function preserves the real exit code of the failed command so your script reports failure accurately to external schedulers and CI runners.

Stage 3: Advanced Tracing and Targeted Debugging

Debugging scripts by adding echo statements is slow and incomplete. Bash provides built-in execution tracing via set -x, along with configurable prompt variables that provide caller context.

You can turn tracing on and off dynamically around suspect sections of code, and you can reformat the PS4 prompt to include the file name, line number, and function name.

bash
#!/usr/bin/env bash
set -euo pipefail

# Enhance the trace prompt: file, line number, and subshell level
export PS4='+ [${BASH_SOURCE[0]}:${LINENO}]: '

validate_archive() {
    local archive_path="$1"
    
    # Enable execution trace inside this function only
    set -x
    test -f "${archive_path}"
    gzip -t "${archive_path}"
    { set +x; } 2>/dev/null
}

RELEASE_ARCHIVE="bundle.tar.gz"

# Create a dummy gzip file to pass validation
echo "test content" | gzip > "${RELEASE_ARCHIVE}"

WORK_DIR=$(mktemp -d)
cleanup() {
    rm -rf "${WORK_DIR}" "${RELEASE_ARCHIVE}"
}
trap cleanup EXIT

echo "Starting validation process..."
validate_archive "${RELEASE_ARCHIVE}"
echo "Validation passed."

The redirected block { set +x; } 2>/dev/null suppresses the trace output of disabling the trace itself, keeping standard error clean.

Common Pitfalls and Edge Cases

Pitfall 1: Subshell masking under set -e

Command substitutions $(...) do not always trigger an exit under set -e when combined with local declarations.

Consider this function:

bash
# BROKEN PATTERN
process_data() {
    local data=$(failing_command)
    echo "Data: ${data}"
}

The command local is itself a command that succeeds (exit code 0), masking the failure inside the subshell. The script will continue running.

To fix this, separate the declaration from the assignment:

bash
# CORRECT PATTERN
process_data() {
    local data
    data=$(failing_command)
    echo "Data: ${data}"
}

Now data=$(failing_command) runs as an independent assignment, and set -e halts execution if failing_command returns non-zero.

Pitfall 2: Handling expected non-zero exits

Sometimes a command is expected to fail or return an exit code other than zero, such as grep searching a file that may not contain the string, or diff identifying changes. Under set -e, this causes an unwanted script termination.

You must neutralize the failure explicitly using the || operator or a default assignment:

bash
# Prevents exit if grep finds zero matches
match=$(grep "optional_key" config.ini || true)

# Reads an optional environment variable with a fallback under set -u
PORT="${SERVICE_PORT:-8080}"

Using || true sets the overall expression return code to 0, satisfying set -e.

Try It Yourself

Write a script named process_logs.sh that meets these requirements:

  1. Enables strict mode (set -euo pipefail).
  2. Creates a temporary work file using mktemp.
  3. Registers a cleanup trap that removes the file when the script terminates.
  4. Uses a pipeline that extracts lines containing the word “ERROR” from a non-existent file server.log, counts the lines with wc -l, and stores the result in a variable inside a function.
  5. Ensures the script halts at the pipeline without crashing silently or running the cleanup out of order.
Solution
bash
#!/usr/bin/env bash
set -euo pipefail

# Initialize temporary storage
TMP_LOG=$(mktemp)

cleanup() {
    local exit_code=$?
    echo "Cleaning up temp file: ${TMP_LOG}"
    rm -f "${TMP_LOG}"
    exit "${exit_code}"
}
trap cleanup EXIT

echo "Processing logs..."

count_errors() {
    local error_count
    # Separate local declaration from pipeline assignment
    error_count=$(cat "server.log" | grep "ERROR" | wc -l)
    echo "${error_count}"
}

total_errors=$(count_errors)
echo "Total errors: ${total_errors}"

Because -o pipefail is active, the failure of cat propagates through grep and wc -l, causing the subshell assignment to fail. The -e flag catches the non-zero status immediately, aborting before the assignment finishes, and the EXIT trap deletes the temporary file.

Parsing structured server logs and tabular text using standard shell loops is slow and prone to word-splitting bugs. Stream editors (sed) and pattern scanners (awk) process lines as continuous streams directly in memory, transforming raw text into structured data before it enters your shell logic.

Diagnosing Broken Stream Transformations

Consider a common scenario: extracting HTTP status codes and calculating response size totals from an Nginx log format, while stripping away the surrounding quotes. A developer writes the following pipeline to normalize log lines, discard requests to static assets, and tally the bytes sent:

bash
# sample_pipeline.sh
cat << 'EOF' > web.log
192.168.1.10 - - [10/Oct/2024:13:55:36] "GET /index.html HTTP/1.1" 200 2326
192.168.1.11 - - [10/Oct/2024:13:55:37] "POST /api/v1/charge HTTP/1.1" 500 524
192.168.1.12 - - [10/Oct/2024:13:55:38] "GET /images/logo.png HTTP/1.1" 200 45120
192.168.1.13 - - [10/Oct/2024:13:55:39] "GET /styles.css HTTP/1.1" 304 0
EOF

sed 's/\/images\/.*//' web.log | awk '{ if ($9 == 200) total += $10 } END { print "Total: " total }'

Running this script yields unexpected results:

text
Total: 0

The output shows zero bytes processed, even though /index.html returned a 200 code with 2326 bytes.

Two critical issues cause this failure:

  1. Destructive substitution instead of filtering in sed: The command s/\/images\/.*// matches /images/ and deletes the rest of the string, but it still passes an empty remainder of the line down the pipe.
  2. Incorrect field splitting in awk: By default, awk splits on consecutive whitespace sequences. Because the request string "GET /index.html HTTP/1.1" contains spaces inside quotes, the field numbering breaks. In this log format, $9 is HTTP/1.1", not the HTTP status code 200. The condition $9 == 200 always evaluates to false.

Inspect how awk sees the line by printing fields explicitly:

bash
awk '{ print "Field 7: " $7, "| Field 9: " $9, "| Field 10: " $10 }' web.log
text
Field 7: /index.html | Field 9: 200 | Field 10: 2326
Field 7: /api/v1/charge | Field 9: 500 | Field 10: 524
Field 7: /images/logo.png | Field 9: 200 | Field 10: 45120
Field 7: /styles.css | Field 9: 304 | Field 10: 0

Field 9 is indeed 200 here because the method was $6. But notice the third line: /images/logo.png is field 7. If sed deletes from /images/ onward, the line becomes:

text
192.168.1.12 - - [10/Oct/2024:13:55:38] "GET 

Now field 9 does not exist on line three. More importantly, using sed to edit text before awk is redundant; awk handles regular expression pattern matching natively without creating a subshell or pipeline buffer.

Here is the corrected, idiomatic pipeline:

bash
awk '$7 !~ /^\/(images|styles)/ && $9 == 200 { total += $10 } END { print "Total: " total }' web.log
text
Total: 2326

Sed Architecture: The Cycle and Pattern Space

sed operates as a cycle. It reads one line from the input stream into a temporary working memory called the pattern space, applies supplied editing commands sequentially, prints the pattern space to standard output, and then empties the pattern space for the next line.

The basic structure of a sed command is:

text
[address]command[arguments]

If you omit the address, sed applies the command to every single line.

bash
cat << 'EOF' > config.txt
# Global Configuration
host = 127.0.0.1
port = 8080
# Timeout in seconds
timeout = 30
EOF

# Substitute default host using an address to target only specific lines
sed '/^host/ s/127\.0\.0\.1/0.0.0.0/' config.txt
text
# Global Configuration
host = 0.0.0.0
port = 8080
# Timeout in seconds
timeout = 30

Controlling Output with Suppression and Flags

By default, sed prints every line after applying all commands. To use sed purely as an extractor or filter, use the -n flag to silence the default cycle print, and explicitly append p to actions you want emitted.

bash
# Print only non-comment, non-empty lines
sed -n -e '/^#/d' -e '/^$/d' -e 'p' config.txt
text
host = 127.0.0.1
port = 8080
timeout = 30

The d command deletes the current pattern space immediately and restarts the cycle with the next input line. Lines reaching the p command are explicitly written to standard output.

Delimiter Substitution

Using / as a delimiter when modifying paths requires escaping every literal slash, leading to unreadable patterns (the leaning toothpick syndrome). sed allows arbitrary characters as delimiters following the s command:

bash
echo "/var/log/nginx/access.log" | sed 's|/var/log|/opt/data|'
text
/opt/data/nginx/access.log

Awk Architecture: Records, Fields, and Blocks

awk structures incoming data into records (lines, by default) and fields (tokens separated by whitespace, by default).

Internal variables drive this behavior:

  • FS: Field Separator. Defaults to " ", which treats runs of spaces and tabs as one delimiter.
  • OFS: Output Field Separator. Defaults to a single space.
  • RS: Record Separator. Defaults to newline (\n).
  • ORS: Output Record Separator. Defaults to newline (\n).
  • NR: Number of Records. Current record index from the start of execution.
  • FNR: File Number of Records. Current record index relative to the current file.
  • NF: Number of Fields. Count of fields detected in the current record.

The execution model follows three stages:

text
BEGIN { instructions executed before reading any input }
pattern { instructions executed for each line matching pattern }
END   { instructions executed after all streams hit EOF }

Every block is optional. A bare block { print $1 } executes for every line. A bare pattern /ERROR/ prints the entire line ($0) for matches.

Structured Extraction with Custom Separators

Consider colon-delimited configuration data like /etc/passwd:

bash
cat << 'EOF' > users.txt
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
appuser:x:1001:1001:Application Service:/home/appuser:/bin/bash
deploy:x:1002:1002:Deploy Tool:/home/deploy:/bin/sh
EOF

awk -F: '$7 == "/bin/bash" { printf "%-10s (UID: %d)\n", $1, $3 }' users.txt
text
root       (UID: 0)
appuser    (UID: 1001)

Setting -F: assigns FS before reading the stream. The condition $7 == "/bin/bash" tests exact field equality rather than a loose substring match.

Edge Cases and Pitfalls

Pitfall 1: Greediness in Regular Expressions

POSIX standard sed uses Basic Regular Expressions (BRE) by default, or Extended Regular Expressions (ERE) with the -E flag. Neither supports non-greedy quantifiers like .*?.

bash
cat << 'EOF' > html.txt
<p>First paragraph</p><p>Second paragraph</p>
EOF

# Broken: .* is greedy and consumes through the last tag
sed -E 's/<p>(.*)<\/p>/\1/' html.txt
text
First paragraph</p><p>Second paragraph

To fix this without non-greedy support, match all characters except the closing boundary using a negated character class [^<]*:

bash
sed -E 's/<p>([^<]*)<\/p>/\1/g' html.txt
text
First paragraphSecond paragraph

Pitfall 2: Modifying Fields Directly in Awk

When you read a field like $1, awk leaves $0 untouched. However, if you mutate any field directly, awk reconstructs the entire $0 buffer using OFS. This side-effect strips original whitespace.

bash
cat << 'EOF' > spacing.txt
one    two        three
EOF

awk '{ print $0 }' spacing.txt
awk '{ $2 = "MODIFIED"; print $0 }' spacing.txt
text
one    two        three
one MODIFIED three

The multiple spaces collapsed into single spaces defined by the default OFS. If formatting must be preserved, use regular expression substitutions (sub or gsub) instead of field assignment.

Pitfall 3: Escaping Shell Variables inside Awk Scripts

Passing Bash variables into awk by breaking out of quotes introduces shell injection flaws and quote syntax errors:

bash
# Fragile and dangerous
TARGET="root"
awk '{ if ($1 == "'"$TARGET"'") print $0 }' users.txt

Instead, use the -v flag to import Bash variables cleanly into awk variables before parsing:

bash
TARGET="root"
awk -v target="$TARGET" -F: '$1 == target { print $0 }' users.txt
text
root:x:0:0:root:/root:/bin/bash

Try It

You have an application log containing log levels, ISO timestamps, client IDs, and response latencies in milliseconds.

bash
cat << 'EOF' > app.log
2024-10-15T08:00:01Z [INFO] client=401 status=200 latency=45ms
2024-10-15T08:00:02Z [WARN] client=503 status=429 latency=12ms
2024-10-15T08:00:03Z [ERROR] client=401 status=500 latency=120ms
2024-10-15T08:00:04Z [ERROR] client=109 status=503 latency=85ms
2024-10-15T08:00:05Z [INFO] client=401 status=200 latency=30ms
EOF

Write a one-line sed and/or awk pipeline that matches only [ERROR] lines, extracts the numeric value of the latency field (without the trailing ms), and outputs the arithmetic average of those error latencies.

Solution
bash
awk '$2 == "[ERROR]" {
    match($5, /latency=([0-9]+)ms/, arr)
    sum += arr[1]
    count++
}
END {
    if (count > 0) {
        print "Average Error Latency:", sum / count, "ms"
    }
}' app.log

Alternatively, standard field splitting without regex captures:

bash
awk '$2 == "[ERROR]" {
    sub(/latency=/, "", $5)
    sub(/ms/, "", $5)
    sum += $5
    count++
}
END {
    if (count > 0) print "Average Error Latency:", sum / count "ms"
}' app.log

Output:

text
Average Error Latency: 102.5ms

awk executes the END block only after reading all records. The condition prevents a division-by-zero error if no lines match [ERROR].

Running commands sequentially wastes time when tasks spend their lifecycle waiting on external resources like disks or networks. Firing them off simultaneously with an ampersand solves the speed issue but immediately introduces synchronization bugs, runaway processes, and resource exhaustion.

The Problem: The Naive Async Pattern

Consider a build step where three independent assets need compilation. The naive approach simply tags an ampersand onto the end of each command and exits.

bash
#!/usr/bin/env bash
set -euo pipefail

echo "Starting build tasks..."

sleep 2 && echo "Assets compiled" &
sleep 1 && echo "Templates generated" &
sleep 3 && echo "Binary built" &

echo "Build complete. Deploying..."

The script prints Build complete. Deploying... immediately, while none of the actual build steps have finished. The shell forks subshells for each background job, prints its own completion message, and terminates.

Worse: if one of those background commands fails, your script will still exit with status 0 because the failure occurs inside an unmonitored background subshell.

Synchronizing Subshells with wait

The wait builtin pauses execution of the current shell until all background child processes finish, or until a specific process identifier (PID) finishes.

When a command is sent to the background via &, Bash records its PID in the special variable $!.

bash
#!/usr/bin/env bash
set -euo pipefail

echo "Starting synchronized tasks..."

sleep 2 && echo "Task A done" &
pid_a=$!

sleep 1 && echo "Task B done" &
pid_b=$!

# Wait for specific processes and capture their exit codes
wait "${pid_a}"
status_a=$?

wait "${pid_b}"
status_b=$?

echo "Task A exit: ${status_a}, Task B exit: ${status_b}"
echo "All tasks resolved."
text
Starting synchronized tasks...
Task B done
Task A done
Task A exit: 0, Task B exit: 0
All tasks resolved.

Calling wait without arguments waits for all currently active child processes. However, plain wait only returns the exit status of the last process that terminated. Storing $! right after spawning allows you to inspect the precise exit code of each job.

Checking Failures Under set -e

In Bash, set -e does not automatically catch background subshell failures at the moment they fail. If an async task exits non-zero, it does not trigger an immediate script exit. The exit status is surfaced only when you call wait on that specific PID:

bash
#!/usr/bin/env bash
set -euo pipefail

false &
bad_pid=$!

echo "Subshell running in background..."
wait "${bad_pid}"
echo "This line will never execute."
text
Subshell running in background...

The script terminates on wait "${bad_pid}" because wait returns the non-zero status of the child, which set -e traps.

Managing Lifecycles with Signals and traps

If your script starts three long-running background tasks and a user presses Ctrl+C (sending SIGINT), the parent script exits. However, the background tasks often keep running as orphaned processes under PID 1 (init or systemd).

To prevent leaks, catch termination signals and cleanly reap child processes.

bash
#!/usr/bin/env bash
set -euo pipefail

declare -a child_pids=()

cleanup() {
    local exit_code=$?
    trap - EXIT
    
    for pid in "${child_pids[@]}"; do
        if kill -0 "${pid}" 2>/dev/null; then
            kill -TERM "${pid}" 2>/dev/null || true
        fi
    done
    
    exit "${exit_code}"
}

# Trap common termination signals
trap cleanup SIGINT SIGTERM EXIT

# Start workers
sleep 50 &
child_pids+=("$!")

sleep 60 &
child_pids+=("$!")

echo "Processes running: ${child_pids[*]}"
wait

kill -0 ${pid} does not send a destructive signal. It checks whether the target PID exists and whether the current user has permission to send signals to it. If it returns 0, the process is alive.

The trap cleanup SIGINT SIGTERM EXIT guarantees that whether the script is aborted with Ctrl+C, terminated by system orchestration, or exits normally, the cleanup function executes. Setting trap ... EXIT also triggers on normal termination, so you must explicitly check if the child processes are still running before trying to kill them. Unsetting the EXIT trap inside the handler (trap - EXIT) prevents the handler from running recursively when exit is called.

Limiting Concurrency with a Job Pool

Firing an unbounded number of background tasks can crash a system by exhausting available file descriptors, memory, or thread limits. You must restrict concurrency to a fixed pool size.

A clean, dependency-free pattern relies on the jobs builtin to monitor running children:

bash
#!/usr/bin/env bash
set -euo pipefail

max_jobs=3

run_worker() {
    local id=$1
    local work_time=$(( (RANDOM % 3) + 1 ))
    sleep "${work_time}"
    echo "Worker ${id} finished after ${work_time}s"
}

for i in {1..8}; do
    run_worker "${i}" &
    
    # Check current active job count
    while [ "$(jobs -r -p | wc -l)" -ge "${max_jobs}" ]; do
        # Wait for the next single job to finish
        wait -n || true
    done
done

# Drain remaining tasks
wait
echo "Batch execution complete."

The flag -n (available in Bash 4.3+) instructs wait to pause until any single background task finishes, rather than waiting for all of them. Adding || true prevents set -e from aborting the loop prematurely if a child job exits with a non-zero status. This loop keeps the concurrency pipeline saturated at exactly max_jobs until the batch completes.

Note that jobs -r -p lists process IDs for currently running jobs. When the count matches or exceeds max_jobs, the script suspends on wait -n.

Common Pitfalls and Edge Cases

Pitfall 1: Subshell Variable Isolation

Background tasks run in separate subshells. Any modification to environment state, shell variables, or directories inside that task will not propagate back to the parent script.

bash
#!/usr/bin/env bash
set -euo pipefail

counter=0

(
    counter=42
    echo "Inside background subshell: ${counter}"
) &

wait
echo "Inside parent process: ${counter}"
text
Inside background subshell: 42
Inside parent process: 0

To return data from a background process, write to a designated temporary file or stream through a FIFO (named pipe), rather than trying to assign to parent shell variables.

Pitfall 2: Process ID Recycling

Linux systems recycle PIDs. If a background job finishes quickly, its PID might be re-assigned to a completely unrelated system process by the time your code evaluates an unquoted or delayed kill "${pid}".

Always capture $! immediately after the command fork. Do not rely on hardcoded process names with tools like killall or pkill in scripts, as this leads to collateral termination of unrelated instances running under the same user.

Pitfall 3: Swallowing Failures with wait -n

Using wait -n simplifies pool management, but it changes how error handling works under set -e. Because wait -n returns the exit code of whichever job finished first, an unhandled failure immediately halts the scheduling loop if set -e is active.

Developers frequently guard against this with wait -n || true. While this keeps the pool loop running, it silently swallows the error code. The parent script has no record of which child failed or why.

bash
# Antipattern: errors vanish completely
while [ "$(jobs -r -p | wc -l)" -ge "${max_jobs}" ]; do
    wait -n || true
done

If you must know whether every job succeeded, you cannot rely entirely on wait -n to track statuses. You must either track individual child PIDs explicitly in an associative array or have each child record its exit status to a known directory on disk.

Worked Example: Parallel Artifact Downloader with Error Collection

The following complete script demonstrates safe concurrency: it limits simultaneous workers, collects individual exit codes and logs from each child without leaking variables, and cancels running siblings if a fatal error occurs.

bash
#!/usr/bin/env bash
set -euo pipefail

readonly MAX_CONCURRENT=3
readonly WORK_DIR="$(mktemp -d)"

cleanup() {
    local exit_code=$?
    trap - EXIT
    # Terminate any remaining background children
    local running
    running=$(jobs -p)
    if [ -n "${running}" ]; then
        kill -TERM ${running} 2>/dev/null || true
    fi
    rm -rf "${WORK_DIR}"
    exit "${exit_code}"
}
trap cleanup SIGINT SIGTERM EXIT

download_artifact() {
    local id=$1
    local dest_file="${WORK_DIR}/artifact_${id}.txt"
    local log_file="${WORK_DIR}/job_${id}.log"

    # Simulate network latency and an intentional failure on ID 4
    {
        echo "Starting download ${id}..."
        sleep "$(( (RANDOM % 2) + 1 ))"
        if [ "${id}" -eq 4 ]; then
            echo "Error: checksum mismatch for artifact ${id}" >&2
            exit 1
        fi
        echo "Payload ${id}" > "${dest_file}"
        echo "Completed download ${id}."
    } > "${log_file}" 2>&1
}

declare -a job_pids=()
declare -A pid_to_id=()

echo "Dispatching downloads..."

for id in {1..6}; do
    download_artifact "${id}" &
    pid=$!
    job_pids+=("${pid}")
    pid_to_id["${pid}"]="${id}"

    while [ "$(jobs -r -p | wc -l)" -ge "${MAX_CONCURRENT}" ]; do
        wait -n || true
    done
done

# Wait for every tracked PID specifically to collect exact statuses
failed=0
for pid in "${job_pids[@]}"; do
    id="${pid_to_id[${pid}]}"
    if wait "${pid}"; then
        echo "Job ${id} (PID ${pid}) succeeded."
    else
        echo "Job ${id} (PID ${pid}) failed with code $?." >&2
        cat "${WORK_DIR}/job_${id}.log" >&2
        failed=1
    fi
done

if [ "${failed}" -ne 0 ]; then
    echo "One or more downloads failed." >&2
    exit 1
fi

echo "All artifacts downloaded successfully."

In this architecture:

  1. download_artifact redirects its stdout and stderr to a unique log file per job. This eliminates interleaved output in the console.
  2. The throttling loop uses wait -n || true strictly to throttle throughput without halting execution on error.
  3. The parent records every PID in job_pids alongside its metadata in pid_to_id.
  4. The post-drain loop explicitly calls wait "${pid}" for every job. Calling wait on an already-terminated PID does not block. It retrieves the retained exit status of that child.
  5. If any task fails, its isolated log file is printed to stderr, and the script exits with code 1.

Try It Yourself

Write a script that processes an array of four file names: file1.log, file2.log, file3.log, and file4.log.

Requirements:

  • Simulate processing by calling sleep 1.
  • Run at most 2 jobs in parallel.
  • Print when each file starts and when it finishes.
  • Collect and print the total number of processed files at the very end.
Solution
bash
#!/usr/bin/env bash
set -euo pipefail

targets=("file1.log" "file2.log" "file3.log" "file4.log")
max_parallel=2
processed_count=0

process_file() {
    local file=$1
    echo "Processing ${file}..."
    sleep 1
    echo "Finished ${file}"
}

for file in "${targets[@]}"; do
    process_file "${file}" &
    processed_count=$((processed_count + 1))
    
    while [ "$(jobs -r -p | wc -l)" -ge "${max_parallel}" ]; do
        wait -n || true
    done
done

wait

echo "Successfully processed ${processed_count} files."

Because processed_count is incremented in the parent process before the wait -n throttling check, it accurately tracks the queued files without running into subshell variable isolation issues.

Shell scripts that accept user input or run with root permissions frequently introduce arbitrary command execution vulnerabilities through word splitting, path traversal, and unvalidated environment expansion. Hardening Bash scripts requires treating all external data as hostile, locking down execution environments, and constraining operations to strict, validated boundaries.

We will build an audit archiving utility named audit-vault.sh. It accepts a tenant identifier and a log filename, verifies the source file, and archives it into an isolated directory structure without allowing command injection or directory traversal.

Stage 1: Strict Execution Environment and Shell Flags

The first line of defense is forcing the shell interpreter to fail fast and reject ambiguous execution states. Most production failures occur because Bash defaults to continuing execution after an error and expands unset variables to empty strings.

bash
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'
umask 077

readonly ARCHIVE_BASE="/var/log/audit_vault"
readonly LOG_INPUT="${1:-}"
readonly TENANT_ID="${2:-}"

if [[ -z "${LOG_INPUT}" || -z "${TENANT_ID}" ]]; then
    echo "Usage: $0 <log_path> <tenant_id>" >&2
    exit 1
fi

echo "Initialized vault job for tenant: ${TENANT_ID}"

Here is why each directive matters:

set -e halts execution if any command exits with a non-zero status. set -E ensures that trap functions inherit error traps (ERR).

set -u treats unset variables as an error, preventing accidental operations on uninitialized names. For example, rm -rf "${TARGET_DIR}/${SUBDIR}" will fail immediately if SUBDIR is not set, instead of deleting the entire root of TARGET_DIR.

set -o pipefail ensures that a pipeline returns the exit status of the last command to exit with a non-zero status, rather than returning the exit status of the very last command.

IFS=