← All free guides
FREE GUIDE · 101 TRICKS · 13 CATEGORIES

100+ Bash
Scripting Tricks

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

101
Tricks
13
Categories
23
Pages
Free
No sign-up

Inside the guide: all 101 tricks

1Fundamentals & Script Structure8 tricks

1.1 Always use a proper shebang

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.

1.2 Make the script executable once and for all

Example: chmod +x my_script.sh — skip typing bash in front of the command every time; just run ./my_script.sh.

1.3 Exit early on error

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.

  • 1.4 Check the exit code explicitly when it matters
  • 1.5 Document the script's purpose at the top
  • 1.6 Use the right exit code to signal the result
  • 1.7 Separate configuration from logic
  • 1.8 Run a syntax check without executing
2Variables & Parameter Expansion10 tricks

2.1 Set default values elegantly

Example: name="${1:-Anonymous}" — uses the first argument if it exists, otherwise "Anonymous", without a separate if statement.

2.2 Require that a variable is set

Example: : "${API_KEY:?The API_KEY environment variable must be set}" — aborts the script with a clear error message if the variable is missing.

2.3 Extract substrings without external tools

Example: ${string:2:5} — grab 5 characters starting at index 2, directly in Bash without calling cut or awk.

  • 2.4 Replace text in a variable directly
  • 2.5 Strip a prefix or suffix from a path
  • 2.6 Swap a file extension in one step
  • 2.7 Uppercase or lowercase a variable's contents
  • 2.8 Count the length of a string or array
  • 2.9 Measure time with microsecond precision
  • 2.10 Use indirect references for dynamic variable names
3Arrays9 tricks

3.1 Declare and loop over an indexed array

Example: fruits=(apple banana pear) and for f in "${fruits[@]}"; do echo "$f"; done — always quote "${array[@]}" to handle elements containing spaces correctly.

3.2 Use associative arrays for key-value data

Example: declare -A config=([host]="localhost" [port]="8080") and echo "${config[host]}" — a built-in alternative to parsing external config files for simple cases.

3.3 Add elements to an array dynamically

Example: fruits+=("mango") — extend an array without rewriting the whole declaration.

  • 3.4 Loop with both index and value
  • 3.5 Split a string into an array
  • 3.6 Join an array into a string
  • 3.7 Remove an element from an array
  • 3.8 Copy an array safely
  • 3.9 Copy an array to another variable without sharing a reference
4Conditionals & Tests9 tricks

4.1 Prefer [[ ]] over [ ] in Bash scripts

[[ ]] 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 [ ].

4.2 Test multiple conditions readably

Example: if [[ -f "$file" && -r "$file" ]]; then ... — combine conditions with && / || directly inside [[ ]] instead of chaining separate test commands.

4.3 Match patterns without regex

Example: if [[ "$filename" == *.log ]]; then ... — glob patterns work directly inside [[ ]] without needing case or external tools.

  • 4.4 Use regular expressions when patterns aren't enough
  • 4.5 Check whether a variable is empty safely
  • 4.6 Test file types before acting on them
  • 4.7 Use case for multi-way choices instead of long if chains
  • 4.8 Check whether a command exists before running it
  • 4.9 Test multiple patterns in a single case branch
5Loops & Flow Control7 tricks

5.1 Loop over files safely, even with spaces in the name

Example: for file in *.txt; do echo "$file"; done — always quote "$file" inside the loop; avoid parsing ls output line by line.

5.2 Read a file line by line correctly

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.

5.3 Break out of nested loops with break N

Example: break 2 exits two nested loop levels in one step instead of setting a flag that the outer loop checks.

  • 5.4 Skip an iteration with continue
  • 5.5 Use C-style for loops for numeric sequences
  • 5.6 Run a loop a fixed number of times without a counter variable
  • 5.7 Create an infinite loop with a clear break condition
6Functions6 tricks

6.1 Define functions with local variables

Example:

my_function() {
    local result="$1"
    echo "$result"
}

— local keeps a function's variables from leaking out and colliding with global variables.

6.2 Return data via stdout, not the return code

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).

6.3 Check the number of arguments before using them

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.

  • 6.4 Use named arguments for readability in complex functions
  • 6.5 Build reusable function libraries
  • 6.6 Use fork-free execution for fast command substitutions
7Error Handling & Debugging8 tricks

7.1 Catch errors with trap

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.

7.2 Clean up resources guaranteed, even on crash

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.

7.3 Identify exactly which signal was caught

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.

  • 7.4 Run the script in debug mode when needed
  • 7.5 Temporarily disable debug output around sensitive sections
  • 7.6 Write error messages to stderr, not stdout
  • 7.7 Validate input before you trust it
  • 7.8 Use a strict error-handling template for new scripts
8Processes, Jobs & Subshells7 tricks

8.1 Run commands in parallel and wait for all of them

Example: command1 & command2 & wait — starts both in the background and waits until both finish before the script continues.

8.2 Wait for a specific background job

Example: command & pid=$!; wait "$pid" — save the PID of the job you actually care about instead of waiting for every background job.

8.3 Capture the exit code from a 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.

  • 8.4 Use process substitution to avoid temp files
  • 8.5 Run a subshell to isolate side effects
  • 8.6 List and manage active background jobs
  • 8.7 Send a process to the background and detach it
9Input/Output & Redirection7 tricks

9.1 Write multi-line text with a heredoc

Example:

cat <<EOF > config.txt
host=localhost
port=8080
EOF

— clearer than multiple echo lines for generating text files in scripts.

9.2 Avoid variable expansion in a heredoc when needed

Example: cat <<'EOF' (with a quoted delimiter) — prevents $var and command substitution from being interpreted inside the heredoc block.

9.3 Discard unwanted output cleanly

Example: command > /dev/null 2>&1 — hide both standard output and error output when you only care about the exit code.

  • 9.4 Read input interactively with readline support
  • 9.5 Send multiple commands' output to the same file
  • 9.6 Read an entire file into a variable
  • 9.7 Write to multiple destinations at once
10Performance & Efficiency7 tricks

10.1 Prefer built-in commands over external processes

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.

10.2 Avoid spawning a subshell unnecessarily

Example: ((counter++)) instead of counter=$(( counter + 1 )) when you just need to increment a value — the former is faster and clearer.

10.3 Read files once instead of opening them repeatedly in loops

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.

  • 10.4 Use printf instead of echo for formatted output
  • 10.5 Sort pathname expansion without an extra process
  • 10.6 Measure a script's performance easily
  • 10.7 Avoid unnecessary calls to external tools for simple checks
11Script Security7 tricks

11.1 Always quote variables that might contain spaces

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.

11.2 Avoid eval unless absolutely necessary

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}.

11.3 Set a safe IFS before parsing external data

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.

  • 11.4 Validate file paths before destructive operations
  • 11.5 Use mktemp for temp files instead of hardcoded names
  • 11.6 Limit what a script can do with least privilege
  • 11.7 Clear sensitive variables after use
12Toolbox & Practical One-Liners8 tricks

12.1 Find and act on files in one sweep

Example: find . -name "*.tmp" -mtime +7 -delete — find files older than 7 days and delete them directly, no intermediate step.

12.2 Run a command for each line from another process

Example: find . -name "*.log" | xargs -I{} gzip {} — compress every log file in a single piped command instead of a manual loop.

12.3 Count occurrences quickly

Example: grep -c "ERROR" log.txt — count matching lines directly without piping to wc -l.

  • 12.4 Generate random values directly in the shell
  • 12.5 Create multiple directories in a tree structure at once
  • 12.6 Rename multiple files according to a pattern
  • 12.7 Chain output from multiple commands conditionally
  • 12.8 Build a simple menu with select
13What's New in Bash 5.38 tricks

13.1 Run commands in the current shell process with ${ ;}

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.

13.2 Get better error messages for invalid variable names

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.

13.3 Take advantage of monotonic clock support

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.

  • 13.4 Check POSIX-compliant umask handling
  • 13.5 Force quoting in printf with %q and %Q
  • 13.6 Sort file matches without external sorting
  • 13.7 Use new loadable builtins for specialized tasks
  • 13.8 Save completion suggestions to a variable
The full guide, as a PDFEvery trick above is written up in full. Free, no email needed.

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.