Bash Best Practices: Writing Safer, Cleaner Scripts

Bash scripts tend to start small and grow over time. A helper you wrote in five minutes to copy a few files can end up running in a cron job, a deployment pipeline, or a server startup script. When that happens, small oversights such as an unquoted variable or an ignored error become real outages.
This guide covers practical Bash best practices that keep scripts predictable, safe to re-run, and easy for other people to read.
Start With a Clear Shebang
Every Bash script should begin with a proper shebang line. The portable choice for Bash is:
#!/usr/bin/env bashUsing /usr/bin/env bash lets the script find Bash through the PATH, which matters on systems where Bash is installed outside /bin, such as macOS with Homebrew. If you rely on features that exist only in Bash, do not use #!/bin/sh. On many distributions /bin/sh points to dash or another minimal shell, and arrays and [[ ]] do not exist there. For a closer look at #!/bin/bash versus #!/usr/bin/env bash, see our Bash shebang
guide.
Enable Strict Mode
By default, Bash ignores many errors. A command can fail, a variable can be unset, and the script will keep running as if nothing happened. Enabling strict mode at the top of the script changes that behavior.
#!/usr/bin/env bash
set -euo pipefailHere is what each flag does:
-e- Exit on many command failures, with exceptions such as commands used in conditions.-u- Treat unset variables as an error and exit.-o pipefail- Make a pipeline fail if any command in it fails, not only the last one.
A common extra is IFS=$'\n\t', which prevents word splitting on spaces and avoids surprises when iterating over filenames that contain spaces.
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'Bash ignores -e inside a function you call in an if condition. The function can continue after a failed command and report success if its last command succeeds. Our Bash strict mode
guide walks through each flag with examples, and the bash set command
guide covers the set builtin on its own.
Always Quote Your Variables
Unquoted variables in Bash are expanded and then word-split. If a variable contains spaces, wildcards, or is empty, the result may be very different from what you expect.
file="My Report.txt"
printf '<%s>\n' $file<My>
<Report.txt>Because $file is not quoted, Bash passes two arguments to printf: My and Report.txt. Quoting fixes it and keeps the filename as one value:
printf '<%s>\n' "$file"<My Report.txt>The same rule applies inside tests, loops, and command substitutions. When in doubt, quote. The only common case where you intentionally leave a variable unquoted is when you want word splitting, which should be rare and deliberate.
Use $() Instead of Backticks
Both `command` and $(command) run a command and substitute its output, but the backtick form causes trouble as soon as a script grows past one-liners.
The first problem is nesting. Backticks do not nest on their own, so every inner pair needs escaping:
echo "`basename \`dirname /var/log/syslog\``"logForget the backslashes and Bash closes the first pair at the wrong place, so basename runs with no argument and dirname /var/log/syslog is left over as plain text. The $(...) form nests without any escaping:
echo "$(basename "$(dirname /var/log/syslog)")"logBackslashes are the second problem. In the following example, Bash turns two backslashes into one before it parses the command inside the backticks.
printf '%s\n' "`printf '%s' \\a`"aBash treats the remaining backslash as an escape for a, so printf prints just a. In the $(...) example below, Bash passes both backslashes to the inner parser.
printf '%s\n' "$(printf '%s' \\a)"\aThe first backslash quotes the second one, so printf prints a literal \a.
Backticks do nothing that $(...) cannot, so make $(...) your default. Quote the result as well, since command substitution is word-split like any other expansion.
Prefer [[ ]] Over [ ]
Bash supports two test constructs: the older [ ] (a synonym for the test command) and the newer [[ ]] keyword. For Bash scripts, prefer [[ ]]:
if [[ -f "$config" && "$env" == "production" ]]; then
echo "Loading production config"
fi[[ ]] handles empty variables safely even without quotes, supports pattern matching with == and regex with =~, and allows logical operators such as && and || inside the test. Only fall back to [ ] when writing a portable POSIX script that must run under sh or dash.
Use Functions for Repeated Logic
Once a script has more than a couple of steps, group related commands into functions. Functions make scripts easier to read, test, and refactor.
log() {
printf '[%s] %s\n' "$(date +'%F %T')" "$*" >&2
}
backup_dir() {
local src="$1"
local dst="$2"
log "Backing up $src to $dst"
rsync -a "$src/" "$dst/"
}
backup_dir "/var/www" "/backup/www"Declare variables inside functions with local so they do not leak into the rest of the script. Pass input as positional parameters, and return output via echo or printf rather than global variables when possible.
The log function writes to stderr
with >&2. When you capture the output of a function with $(...), the log lines stay out of the result.
See Bash functions for more details on arguments, return values, and scoping.
Build Command Arguments With Arrays
Quoting protects a single value, but scripts often need to build a whole list of arguments and hand it to a command. Packing that list into a plain string does not work, because the string is word-split on every space and the quotes inside it are never re-parsed:
opts="--exclude 'My Report.txt'"
printf '<%s>\n' $opts<--exclude>
<'My>
<Report.txt'>The filename was split in two, and the single quotes came through as literal characters. An array keeps every argument intact:
opts=(--exclude "My Report.txt")
printf '<%s>\n' "${opts[@]}"<--exclude>
<My Report.txt>Expanding with "${opts[@]}" produces one shell word per element, whatever those elements contain. In the following script, the first two arguments are the source and destination directories. Pass yes as the third argument to add --verbose.
#!/usr/bin/env bash
src=${1:?Pass a source directory}
dst=${2:?Pass a destination directory}
args=(-a)
if [[ "${3:-}" == "yes" ]]; then
args+=(--verbose)
fi
rsync "${args[@]}" -- "$src/" "$dst/"Keep both the quotes and the @ subscript. "${opts[*]}" joins every element into a single word, and an unquoted ${opts[@]} word-splits again, which puts you back where you started. See Bash arrays
for indexing, slicing, and the rest of the array syntax.
Handle Errors Explicitly
An ERR trap can log a failed command’s line number and exit status. The snippet below defines a handler and registers it near the start of the script.
#!/usr/bin/env bash
set -Eeuo pipefail
on_error() {
local exit_code=$?
local line=$1
echo "Error on line $line (exit code $exit_code)" >&2
exit "$exit_code"
}
trap 'on_error $LINENO' ERRThe -E option passes the ERR trap into functions, command substitutions, and subshells. Bash still skips the trap in the same conditions where it ignores -e.
When you call a function in an if condition, check the commands the rest of the function depends on. The || return 1 below stops the function before it can print a success message for a missing or unreadable file.
check_config() {
[[ -f "$1" && -r "$1" ]] || return 1
printf 'Config is readable\n'
}
config=${1:-settings.conf}
if ! check_config "$config"; then
printf 'Cannot read %s\n' "$config" >&2
exit 1
fiFor cleanup tasks such as removing temporary files, use trap on EXIT:
tmp_dir=$(mktemp -d) || exit 1
trap 'rm -rf -- "$tmp_dir"' EXITThe EXIT trap runs when Bash exits, including after a failure that triggers set -e. If a successful exec replaces Bash or SIGKILL terminates it, the cleanup is skipped.
Validate Input Early
Scripts that take arguments should fail fast when those arguments are missing or invalid. Check them before doing any work:
if [[ $# -lt 2 ]]; then
echo "Usage: $0 <environment> <version>" >&2
exit 1
fi
env="$1"
version="$2"
case "$env" in
staging|production) ;;
*)
echo "Unknown environment: $env" >&2
exit 1
;;
esacFor scripts with several flags, use getopts
instead of parsing $@ manually. It handles short options, arguments, and error reporting in a consistent way.
Avoid Parsing the Output of ls
A common beginner mistake is looping over ls output:
for f in $(ls /var/log); do
echo "$f"
doneThis breaks on filenames with spaces, newlines, or special characters. Use a glob or find instead:
for f in /var/log/*; do
echo "$f"
doneIf the directory is empty, the glob
matches nothing. The loop then runs once with the literal string /var/log/* as $f. To make an unmatched pattern expand to nothing, set shopt -s nullglob before the loop.
For recursive traversal, use find with -print0 and xargs -0, or a while read loop with IFS= and -d '' to handle unusual filenames correctly.
Keep Scripts Idempotent When Possible
A script you can safely re-run is much easier to work with than one that breaks on the second attempt. You can run this mkdir -p command again even if the directory already exists.
mkdir -p /opt/app/configUse ln -sfn to update a path your script already manages as a symlink. The -n flag stops ln from following a symlink to a directory. Check the destination first. If the path is a real directory, ln creates a link inside it. The -f flag can replace a regular file. See our ln command
guide for more on replacing links.
The same pattern applies to package installation, user creation, and configuration edits. Tools like Ansible enforce idempotency by design; in Bash, you have to add those checks yourself.
Use Shellcheck
Shellcheck
is a static analyzer for shell scripts. It catches unquoted variables, unsafe for loops, and many other common mistakes before you hit them in production.
On Ubuntu, Debian, and Derivatives, install it with apt:
sudo apt install shellcheckOn Fedora, RHEL, and Derivatives, the package is named ShellCheck. On RHEL and its rebuilds, you need to enable the EPEL repository first:
sudo dnf install ShellCheckThen run it against your script:
shellcheck script.shFix the warnings it raises. When a check does not apply to your script, disable it on the line above the command and record the reason:
# shellcheck disable=SC2016 # write the literal line, expand it later
echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrcWithout the directive, Shellcheck reports SC2016 on the echo line, a warning that expressions do not expand in single quotes. Here the single quotes are intentional. You want $HOME and $PATH to land in ~/.bashrc unexpanded.
Making shellcheck part of your editor or pre-commit hook removes an entire class of Bash bugs.
Prefer Readable Over Clever
Bash is full of shortcuts and obscure expansions. They can make scripts shorter, but they also make them harder to read six months later. Choose the clearer form, even when it is a few characters longer.
if [[ -z "${name:-}" ]]; then
name="anonymous"
fiis almost always easier to maintain than the golfed equivalent:
: "${name:=anonymous}"The ${name:-} expansion keeps the test working under set -u. If you write a plain "$name" and the variable was never set, the script stops with name: unbound variable.
Aim for scripts that a teammate can read once and understand, not ones that require a reference manual.
Quick Reference
For a printable quick reference, see the Bash cheatsheet .
Before committing a Bash script, confirm the following:
#!/usr/bin/env bashshebang is present.set -euo pipefailis enabled.- All variable expansions are quoted.
- Command substitution uses
$(...), not backticks. - Tests use
[[ ]]instead of[ ]. - Functions replace long repeated blocks, with
localvariables. - Argument lists are built as arrays and expanded as
"${arr[@]}". - Critical commands have explicit error checks, and an
EXITtrap cleans up temporary files. - Input is validated before work begins.
- No parsing of
lsoutput. shellcheckreports no warnings, or they are explicitly ignored.
FAQ
Is set -e enough on its own?
Use -u to catch unset variables and -o pipefail to catch failures earlier in a pipeline. The exceptions for -e still apply, so check failures explicitly inside functions you use as conditions.
Does strict mode break existing scripts?
It often surfaces bugs that were already there, such as unset variables and ignored errors. The fix is to quote variables, use default values like ${VAR:-}, and handle expected failures with || true.
Should I write scripts in Bash or switch to Python?
Bash is a good fit for short glue scripts that mostly call other commands. Once a script grows past a few hundred lines, has complex data structures, or needs proper error handling and testing, Python or another language is usually a better choice.
Where can I learn more safe scripting patterns?
Keep the Shellcheck wiki
open while you write. Each warning code has its own page that explains why the pattern is risky and how to fix it. For the exact behavior of set, trap, and other builtins, see the official Bash manual
.
Conclusion
Run shellcheck before committing a script, then test the failure paths yourself. Start with a missing input file or a failed command inside a function you call from if.
Tags
Linuxize Weekly Newsletter
A quick weekly roundup of new tutorials, news, and tips.
About the authors

Dejan Panovski
Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 1000+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.
View author page