Bash Scripting: Practical Basics

Bash is the standard shell on Linux. Scripts automate recurring tasks.

Basic skeleton

#!/usr/bin/env bash
set -euo pipefail   # fail fast, undefined variables, pipe failures

NAME="${1:-World}"
echo "Hello, $NAME!"

Variables and conditions

if [[ -f /etc/hostname ]]; then
  echo "File exists"
fi

for f in *.log; do
  echo "Processing $f"
done

Functions

log() { echo "[$(date +%H:%M:%S)] $*"; }
log "Starting job"

Error handling

  • set -e aborts on error.
  • Check exit codes: command || echo "Error".
  • trap 'cleanup' EXIT cleans up.
  • Use stderr: echo "Error" >&2.

Pitfalls

  • Always quote variables: "$var".
  • Don't parse ls — use globbing.
  • Bash vs. sh: the shebang decides.

See also: System Administration.