Writing your first Bash script
Turn a sequence of commands you type every day into a small, reliable script.
The skeleton
#!/usr/bin/env bash
set -euo pipefail
name="${1:-world}"
echo "Hello, ${name}!"set -euo pipefail makes the script stop on errors, on unset variables and on failures inside pipelines.
Loops and conditions
for f in *.log; do
if [[ -s "$f" ]]; then
gzip "$f"
fi
done
Quoting
Always quote variables: "$file" instead of $file. Unquoted variables break on spaces and are the most common source of shell bugs.
Check your work
Run shellcheck script.sh. It catches quoting mistakes and many subtle problems before they bite.