A first script
#!/usr/bin/env bash
set -euo pipefail
name="${1:-world}"
echo "Hello, $name"
for f in *.log; do
[ -e "$f" ] || continue
echo "Compressing $f"
gzip -k "$f"
done
Save it as hello.sh, make it executable with chmod +x hello.sh and run ./hello.sh Ada.
Good habits
- Quote variables:
"$file", not$file - Stop on errors with
set -euo pipefail - Test scripts on copies of your data
- Check your scripts with a linter such as ShellCheck
Handling arguments and options
Most scripts become awkward not because of the work they do, but because they accept unclear input. Check arguments near the top, print a short usage message, and exit with a non-zero status when something is missing.
A simple pattern is:
usage() { printf 'Usage: %s [-n] source dest\n' "${0##*/}" >&2; exit 2; }
dry_run=0
while getopts ':n' opt; do
case "$opt" in
n) dry_run=1 ;;
*) usage ;;
esac
done
shift "$((OPTIND - 1))"
[ "$#" -eq 2 ] || usage
getopts is enough for many small Bash tools. After option parsing, use shift so $1 and $2 refer to the real operands. For simple subcommands, a plain case "$1" in start|stop|status) is often clearer than trying to be too clever. When you pass all remaining arguments to another command, use "$@", not $@, so names with spaces stay intact.
Two small habits save a lot of trouble on the Command line:
- Use
--before a filename when a command might mistake it for an option, for examplerm -- "$file". - Test what happens with awkward names such as
report 1.txtor-old.log, not just tidy examples.
These checks matter any time a script touches the File system. A friendly usage line and careful argument handling make the script safer for other people and for your future self.
Functions, output and exit status
Once a script grows beyond a few lines, split it into functions. A common pattern is to define helper functions first, put the main flow in main(), and finish with main "$@". That gives the script one obvious entry point and makes individual pieces easier to test.
Keep functions small and give them one job. Use local for variables inside a function so temporary values do not leak into the rest of the script.
log() { printf '%s\n' "$*" >&2; }
is_root() { [ "${EUID:-$(id -u)}" -eq 0 ]; }
Remember that return is only for a status code, normally 0 for success and non-zero for failure. If a function needs to produce data, print it and capture it with command substitution:
archive_name() { printf '%s.tar.gz\n' "$1"; }
out=$(archive_name "project")
That separation keeps scripts readable: status says whether something worked, standard output carries the result.
printf is usually better than echo for messages that must be predictable. Different shells treat echo -n and backslash escapes differently, while printf behaves consistently.
If a script needs elevated privileges, check early and stop with a clear message rather than failing halfway through. That is especially important when changing ownership, modes, or system files; the background on Users & permissions is worth reviewing if those checks feel unfamiliar.
Temporary files, traps and debugging
Many useful scripts need scratch space. Avoid inventing temporary names such as /tmp/myscript.$$. They can collide with existing files and may expose data you did not mean to leave behind. Instead, create a private temporary directory with mktemp -d and remove it on exit.
tmpdir=$(mktemp -d) || exit 1
cleanup() { rm -rf -- "$tmpdir"; }
trap cleanup EXIT INT TERM
Using a directory is often simpler than juggling several temp files. Put all temporary output inside it, and the trap will tidy up whether the script finishes normally or is interrupted with Ctrl+C.
When a script misbehaves, start with tracing. Run it as bash -x script.sh to see each command after expansion, or place set -x around a suspicious block and set +x after it. For awkward variable values, printf '%q\n' "$var" is handy because it shows spaces and special characters clearly. If output may include secrets, do not leave tracing enabled longer than necessary.
One caveat: set -e does not explain failures for you. A script is much easier to diagnose if you also print explicit error messages, such as log 'backup directory not found', before returning non-zero. Good scripts fail loudly, clean up after themselves, and leave enough clues for later Troubleshooting.
