Practical tricks for faster, safer, and more readable Bash scripts, from the basics to the latest additions in Bash 5.3.

Example: #!/usr/bin/env bash at the top of the file — more portable than #!/bin/bash because it finds bash via PATH no matter where it's installed.
Example: chmod +x my_script.sh — skip typing bash in front of the command every time; just run ./my_script.sh.
Example: set -euo pipefail at the top of the script — -e aborts on error, -u catches uninitialized variables, -o pipefail makes a pipe fail if any stage of it fails, not just the last one.
Example: name="${1:-Anonymous}" — uses the first argument if it exists, otherwise "Anonymous", without a separate if statement.
Example: : "${API_KEY:?The API_KEY environment variable must be set}" — aborts the script with a clear error message if the variable is missing.
Example: ${string:2:5} — grab 5 characters starting at index 2, directly in Bash without calling cut or awk.
Example: fruits=(apple banana pear) and for f in "${fruits[@]}"; do echo "$f"; done — always quote "${array[@]}" to handle elements containing spaces correctly.
Example: declare -A config=([host]="localhost" [port]="8080") and echo "${config[host]}" — a built-in alternative to parsing external config files for simple cases.
Example: fruits+=("mango") — extend an array without rewriting the whole declaration.
[[ ]] is a Bash built-in construct that handles string comparisons, pattern matching, and logical operators more safely and with fewer quoting pitfalls than the POSIX-compatible [ ].
Example: if [[ -f "$file" && -r "$file" ]]; then ... — combine conditions with && / || directly inside [[ ]] instead of chaining separate test commands.
Example: if [[ "$filename" == *.log ]]; then ... — glob patterns work directly inside [[ ]] without needing case or external tools.
Example: for file in *.txt; do echo "$file"; done — always quote "$file" inside the loop; avoid parsing ls output line by line.
Example: while IFS= read -r line; do echo "$line"; done < file.txt — IFS= preserves leading/trailing whitespace and -r stops backslashes from being interpreted as escape sequences.
Example: break 2 exits two nested loop levels in one step instead of setting a flag that the outer loop checks.
Example:
my_function() {
local result="$1"
echo "$result"
}— local keeps a function's variables from leaking out and colliding with global variables.
Bash's return code is limited to 0–255 and meant for status codes. Send actual data by writing to stdout and capturing it with result=$(my_function).
Example: if [[ $# -lt 2 ]]; then echo "Usage: $0 <arg1> <arg2>" >&2; exit 1; fi — give a clear error message instead of cryptic failures further down the script.
Example: trap 'echo "Error on line $LINENO" >&2' ERR — automatically run an action the moment a command fails, with the line number for fast debugging.
Example: trap 'rm -f "$tempfile"' EXIT — the temp file is removed regardless of whether the script exits normally, with an error, or is interrupted with Ctrl+C.
Example: in Bash 5.3, $BASH_TRAPSIG holds the numeric signal number inside a trap handler — handy when the same handler function is used for multiple signals.
Example: command1 & command2 & wait — starts both in the background and waits until both finish before the script continues.
Example: command & pid=$!; wait "$pid" — save the PID of the job you actually care about instead of waiting for every background job.
In Bash 5.3, wait can return the status code of a specific job more reliably — combine with $? right after wait "$pid" to check whether the background job succeeded.
Example:
cat <<EOF > config.txt
host=localhost
port=8080
EOF— clearer than multiple echo lines for generating text files in scripts.
Example: cat <<'EOF' (with a quoted delimiter) — prevents $var and command substitution from being interpreted inside the heredoc block.
Example: command > /dev/null 2>&1 — hide both standard output and error output when you only care about the exit code.
Use Bash's own ${variable//search/replace} instead of calling sed, or arithmetic with (( )) instead of expr — every avoided process start saves time, especially in loops that run thousands of times.
Example: ((counter++)) instead of counter=$(( counter + 1 )) when you just need to increment a value — the former is faster and clearer.
Load the whole file into an array with mapfile -t lines < file.txt and then loop over the array, instead of calling sed -n or head per iteration.
Example: rm "$file" instead of rm $file — an unquoted variable can be interpreted as several separate arguments if the value contains spaces or special characters.
eval runs arbitrary text as code, a classic source of command injection if the text comes from external input. Look for a safer alternative first, like arrays or ${!variable}.
Example: IFS=$'\n\t' — restrict the field separator to newline and tab instead of Bash's default (space, tab, newline), reducing the risk of unexpected word splitting.
Example: find . -name "*.tmp" -mtime +7 -delete — find files older than 7 days and delete them directly, no intermediate step.
Example: find . -name "*.log" | xargs -I{} gzip {} — compress every log file in a single piped command instead of a manual loop.
Example: grep -c "ERROR" log.txt — count matching lines directly without piping to wc -l.
The new ${ command; } syntax executes a command in the same shell process instead of creating a subshell, making command substitution noticeably faster in performance-sensitive scripts.
Bash 5.3 gives clearer diagnostics when a script tries to create or use an invalid variable name (one containing a hyphen, for example), making debugging faster.
Example: $BASH_MONOSECONDS gives you access to a monotonic clock unaffected by system clock adjustments — more reliable than $SECONDS for measuring elapsed time in long-running scripts.
Related guides: 100+ Linux Commands, 100 Unusual & Obscure Linux Commands. From the books: Bash, Distilled — Not Stirred for scripting. All free guides are in the library.