Bash how-to guides

Practical Bash how-to guides for debugging, syntax checks, error handling, arguments and safe scripting, with step-by-step code.

Follow practical, step-by-step guides for common Bash tasks. Published guides include commands, examples, verification steps and common mistakes.

  • How to debug a Bash script

    To debug a Bash script, run `bash -n script.sh` to catch syntax errors without executing, add `set -x` to trace every command as it runs, set a richer `PS4` for line numbers, install ShellCheck for static analysis, and add `trap 'echo "error on line $LINENO"' ERR` to pinpoint failures.

  • How to handle errors in Bash

    Start every script with `set -euo pipefail`. Add `trap 'echo "error on line $LINENO" >&2' ERR` to surface the failure point. For commands that may legitimately fail, handle the exit code explicitly with `if ! cmd; then ...; fi` instead of relying on set -e alone.

  • How to pass arguments to a Bash script

    Inside the script, positional arguments are $1, $2, $3 (up to $9 unbraced; ${10} after that). $@ is all of them as separate words, $# is the count. For named flags (`--verbose`), use getopts (POSIX, single-letter) or a manual while/case loop (long options).

  • How to write a safe Bash script

    A safe Bash script starts with `set -euo pipefail`, quotes every variable, uses mktemp for temp files, cleans up with `trap ... EXIT`, validates input, never pipes curl to bash without checksum, and avoids `rm -rf "$VAR/"` patterns where VAR could be empty.

  • How to compare strings in Bash

    Use `[[ "$a" == "$b" ]]` for equality and `[[ "$a" != "$b" ]]` for inequality. Always quote both sides. Use `<` and `>` inside `[[ ]]` for lexical ordering (unquoted operators, since Bash needs to distinguish them from redirection). Avoid the single-bracket `[ "$a" = "$b" ]` unless you need POSIX portability.

  • How to check if a file exists in Bash

    Use `[ -e "$file" ]` to check that a path exists at all, `[ -f "$file" ]` to require it be a regular file, and `[ -d "$file" ]` to require a directory. Always quote the variable to handle spaces and empty values safely.

  • How to split a string in Bash

    The safest way to split a string on a delimiter is `IFS="," read -ra parts <<< "$str"`, which fills the array `parts` correctly even with special characters. For simple whitespace splitting, unquoted `$str` word-splits automatically, but that is fragile — prefer the explicit `read -ra` form.

  • How to get the directory of a running Bash script

    Use `dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"` to get the absolute directory containing the running script, independent of the current working directory. Add `readlink -f` first if the script may be invoked through a symlink.

  • How to check a command's exit code in Bash

    Read `$?` immediately after a command to get its exit status (0 = success, non-zero = failure). Prefer testing directly with `if command; then` over capturing `$?` separately, since any command in between overwrites `$?`. For pipelines, use `${PIPESTATUS[@]}` to see every stage's exit code.

  • How to run a command in the background in Bash

    Append `&` to run a command in the background and get your prompt back immediately. Capture its PID with `$!`, wait for it (and get its exit status) with `wait "$pid"`, and use `nohup command &` or `disown` if the command must survive terminal/session closure.

  • How to parse command-line flags in Bash with getopts

    Use the `getopts` builtin in a `while getopts ":a:bh" opt; do case $opt in ... esac; done` loop to parse short flags like -a value, -b, and -h. Colons in the option string mark flags that require an argument; a leading colon enables silent error handling so you can report custom usage messages.

  • How to write a Bash function

    Define a function with `name() { ...; }`, access its arguments as $1, $2, "$@" just like a script, and always declare internal variables with `local` to avoid leaking into the caller's scope. Use `return` only for a numeric exit status (0-255); to return actual data, `echo` it and capture with command substitution.

  • How to trap signals in Bash

    Use `trap 'command' SIGNAL` to run code when a script receives a signal. `trap cleanup EXIT` is the standard pattern for guaranteed cleanup (temp files, locks) regardless of how the script exits — normal completion, error, or Ctrl-C. Use `trap '...' ERR` combined with `set -e` to react to any failing command.

  • Bash for loop — complete guide

    Use `for item in list; do ... done` to iterate. Quote the variable inside the body. For numeric ranges use `{1..5}` or `seq`. For files use globs directly, not `$(ls)`. For arrays use `"${arr[@]}"`.

  • Bash if statement — syntax and examples

    Use `if [[ "$x" == "value" ]]; then ... fi` for string tests in Bash. Use `(( a > b ))` for arithmetic. Quote variables in [ ] and [[ ]] to avoid word-splitting. Chain with `&&` and `||` inside [[ ]] or use `elif` for multiple branches.

  • Bash try/catch — error handling patterns

    Bash does not have try/catch. Use `set -euo pipefail` to abort on errors, `||` for per-command recovery, and `trap ERR` for a global handler. For cleanup, use `trap EXIT`.