⚡ 100% In-Browser & Private: Your data never leaves your computer. Powered by Cloudflare Edge CDN.
ProWebTools PRO
Developer & SEO Utilities
30+ Recipes

Bash Scripting Commands & Syntax Matrix

The definitive Bash scripting quick reference: strict mode (set -euo pipefail), parameter expansion, regex matching, line-by-line file loops, and exit traps with 1-click copy.

Shebang & Strict Mode (3 commands)

Shebang & Strict Mode
#!/usr/bin/env bash

Universal bash shebang that finds the bash executable in user PATH.

PRO TIP Prefer over #!/bin/bash for portability across BSD, macOS, and Linux.
Shebang & Strict Mode
set -euo pipefail

Bash unofficial strict mode: exits on error (-e), undefined vars (-u), and pipe failures.

PRO TIP Put this at line 2 of every production bash script to prevent silent catastrophic failures.
Shebang & Strict Mode
IFS=$'\n\t'

Sets Internal Field Separator to newline and tab only, preventing word splitting on spaces.

PRO TIP Essential when iterating over filenames that contain spaces.

Variables & Special Parameters (6 commands)

Variables & Special Parameters
MY_VAR="production"

Assigns a string variable without spaces around the equal sign.

PRO TIP Spaces around "=" cause bash to treat variable name as a command.
Variables & Special Parameters
readonly API_KEY="secret"

Declares an immutable constant variable that cannot be reassigned or unset.

PRO TIP Prevents accidental overwrites in large automation scripts.
Variables & Special Parameters
echo "$1" "$2" "$@"

Accesses script arguments: $1 is first argument, $2 is second, $@ represents all arguments.

PRO TIP Always quote "$@" to preserve arguments containing spaces.
Variables & Special Parameters
echo "$#"

Returns the total number of arguments passed to the script or function.

PRO TIP Combine with if [ "$#" -lt 1 ]; then echo "Missing arg"; fi for validation.
Variables & Special Parameters
echo "$?"

Returns the exit status code of the most recently executed command (0 = success).

PRO TIP Non-zero exit codes (1-255) signal command failure.
Variables & Special Parameters
echo "$$"

Outputs the Process ID (PID) of the currently running script.

PRO TIP Useful for generating unique temporary files: /tmp/job_$$.log.

String & Parameter Expansion (6 commands)

String & Parameter Expansion
${VAR:-"default_value"}

Returns default value if $VAR is unset or empty without mutating VAR.

PRO TIP Perfect for configurable environment variables: PORT=${PORT:-8080}.
String & Parameter Expansion
${VAR:="default_value"}

Sets $VAR to default value if unset or empty, and returns it.

PRO TIP Mutates the variable in the current shell session.
String & Parameter Expansion
${#VAR}

Returns the character length of the string stored in $VAR.

PRO TIP Useful for input validation before processing.
String & Parameter Expansion
${FILE%.*}

Strips file extension from filename (removes shortest trailing match of ".*").

PRO TIP If FILE="backup.tar.gz", ${FILE%.*} outputs "backup.tar".
String & Parameter Expansion
${FILE##*.}

Extracts file extension (removes longest leading match up to ".").

PRO TIP If FILE="photo.2026.png", ${FILE##*.} outputs "png".
String & Parameter Expansion
${VAR//search/replace}

Replaces all occurrences of "search" pattern with "replace" in $VAR.

PRO TIP A single slash ${VAR/search/replace} replaces only the first occurrence.

Conditionals & Tests (5 commands)

Conditionals & Tests
if [[ -f "$FILE" ]]; then ... fi

Tests if $FILE exists and is a regular file.

PRO TIP Prefer [[ ... ]] over single [ ... ] in bash for regex and logical operator support.
Conditionals & Tests
if [[ -d "$DIR" ]]; then ... fi

Tests if directory exists on filesystem.

PRO TIP Use [[ ! -d "$DIR" ]] to test if directory does NOT exist.
Conditionals & Tests
if [[ -z "$STRING" ]]; then ... fi

Tests if string is empty (length zero).

PRO TIP Opposite is [[ -n "$STRING" ]] to test if string is non-empty.
Conditionals & Tests
if [[ "$NUM" -eq 10 && "$NUM2" -gt 5 ]]; then ... fi

Numerical comparisons: -eq (equal), -ne (not equal), -gt (greater), -lt (less), -ge, -le.

PRO TIP Do not use == or > for numbers in bash tests; use -eq and -gt.
Conditionals & Tests
if [[ "$EMAIL" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]]; then ... fi

Performs regex pattern matching using bash built-in =~ operator.

PRO TIP Do not quote the regex pattern on the right side in modern bash.

Loops & Iteration (3 commands)

Loops & Iteration
for file in /path/*.log; do [ -e "$file" ] || continue; echo "$file"; done

Safely iterates over files matching glob pattern, checking existence first.

PRO TIP Prevents errors if no files match the wildcard pattern.
Loops & Iteration
for i in {1..10}; do echo "Step $i"; done

Generates and iterates through numerical range sequence.

PRO TIP Can also specify step increment: {1..100..5}.
Loops & Iteration
while IFS= read -r line; do echo "$line"; done < input.txt

Line-by-line file reader preserving leading/trailing spaces and backslashes.

PRO TIP The gold standard pattern for parsing text files in bash without data corruption.

Functions & Traps (3 commands)

Functions & Traps
log_info() { echo "[$(date +'%Y-%m-%d %H:%M:%S')] INFO: $*"; }

Defines a reusable logging function with ISO timestamp.

PRO TIP Functions receive arguments in $1, $2, and $*.
Functions & Traps
cleanup() { rm -rf "$TEMP_DIR"; echo "Cleaned up"; } trap cleanup EXIT

Registers an exit trap handler that executes automatically on script termination.

PRO TIP Runs even on unexpected errors, SIGINT (Ctrl+C), or normal exit.
Functions & Traps
trap 'echo "Error on line $LINENO"' ERR

Catches any failing command and prints exact file line number where failure occurred.

PRO TIP Invaluable for debugging large unattended deployment scripts.

Redirection & Streams (4 commands)

Redirection & Streams
command > output.log 2>&1

Redirects both standard output (stdout) and standard error (stderr) to file.

PRO TIP Modern bash shortcut: command &> output.log.
Redirection & Streams
command 2>/dev/null

Silences all error messages by sending stderr to /dev/null black hole.

PRO TIP Useful for probe commands like which docker 2>/dev/null.
Redirection & Streams
echo "hello" | tee -a script.log

Prints output to terminal while simultaneously appending it to a log file.

PRO TIP Use -a flag for append; omitting -a overwrites the destination file.
Redirection & Streams
cat << 'EOF' > config.yml server: port: 8080 EOF

Here-document (heredoc) that writes multi-line string to file.

PRO TIP Quoting 'EOF' disables variable expansion, preserving literal $ variables in config.