Bash Automation and Scripting Fundamentals

Executing Shell Programs

Scripts are invoked by specifying the interpreter or making them executable. The standard approach involves passing arguments directly to the program.

#!/bin/bash
./automation_runner.sh --verbose flag-one

Quoting and Substitution Mechanics

Proper handling of strings prevents unexpected parsing errors.

  • Backticks: Legacy command substitution syntax `date`.
  • Dollar Parentheses: Modern alternative $(date) preferred for nesting.
  • Double Quotes: Permit variable expansion within a string context.
  • Single Quotes: Force literal interpretation of all characters, disabling expansion.

Example of safe execution:

echo $(whoami) > current_user.txt

Process Longevity

To maintain execution after shell termination, combine output redirection with background jobs.

nohup long_running_task &

The ampersand suspends foreground control, while nohup ignores hangup signals. Without &, the process remains in the foreground even if nohup is used.

Parameter Expansion Techniques

Manipulate variables without external tools using bash faetures.

filepath="./docs/report_final.pdf"
basename="${filepath##*/}"
dirname="${filepath%/*}"
echo "File: $basename, Path: $dirname"

To strip specific patterns from ends:

config_name="production-config-v1"
cleaned="${config_name%-v1}"

Control Flow Structures

Conditional logic requires spacing around operators inside brackets.

env_type="staging"
if [[ "$env_type" == "prod" ]]; then
    echo "Production Mode Active"
elif [[ ! -f "/etc/config.ini" ]]; then
    echo "Config missing"
else
    echo "Development Environment"
fi

Numeric comparisons utilize flags like -lt (less than), -gt (greater than), and -eq (equal).

Loop Constructs

Iterative operations can be range-based or list-based.

# Range iteration
for cycle in {1..5}; do
    printf "Cycle %d\n" "$cycle"
done

# List iteration
servers=("web01" "db01" "cache01")
for host in "${servers[@]}"; do
    ping -c 2 "$host"
done

While loops continue until a condition fails.

total=0
while [ $total -le 20 ]; do
    ((total += 3))
done

Directory Navigation

Resolve script location dynamically at runtime.

script_dir=$(cd "$(dirname "$0")" ; pwd)
base_name=$(basename "$0")
echo "Location: $script_dir / Name: $base_name"

File System Checks

Validate resources before modification.

target_file="/var/log/app.log"
if [ -f "$target_file" ] && [ -r "$target_file" ]; then
    cat "$target_file"
else
    exit 1
fi

Common tests include -d (directory) and -x (executable).

Exit Codes and Status

Inspect return values immediately after commands.

mkdir /tmp/test_dir
status=$?
if [ $status -eq 0 ]; then
    echo "Success"
fi

Special variables track environment state:

  • $?: Last exit code.
  • $$: Current shell PID.
  • $!: Most recent background PID.
  • $@: Array of positional parameters (preserves quotes).
  • $*: Single string of all parameters.
  • $#: Count of arguments passed.

Link Management

Symboilc links allow references without data duplication.

ln -s source_module.so libmodule.so

This creates a pointer to the original content located elsewhere.

Output Redirection

Manage stdout and stderr streams explicitly.

> empty.txt          # Truncate file
>> append.txt        # Add content
program > out.log 2>&1 # Redirect error to stdout

Search Operations

Utilize find to locate files recursively or within limits.

find /opt -maxdepth 1 -type f -name "*.conf" -printf "%m|%p\n"

Use -print0 with xargs for filenames containing spaces.

Cross-Platform Encoding

Fix line endings when transferring scripts between Windows and Linux.

sed -i 's/\r$//' script_windows.bat
# Or
dos2unix file.sh

Carriage returns (\r) cause shell syntax errors on Unix systems.

Defensive Coding

Avoid empty variable comparison errors by prefixing values.

[[ "x$VAR" == "xvalue" ]] || true

Checking for zero length strings is done with -z.

Tags: shell-scripting linux-bash automation devops unix-tools

Posted on Sat, 09 May 2026 05:00:09 +0000 by dzekic