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"
doneFunctions
log() { echo "[$(date +%H:%M:%S)] $*"; }
log "Starting job"Error handling
set -eaborts on error.- Check exit codes:
command || echo "Error". trap 'cleanup' EXITcleans 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.