โฑ๏ธ Estimated read: 7 min
|
|
A compact reference for everything covered in the Bash Scripting series. Tables only, no prose. Use it during script writing and debugging.
Quick How-To Guides & Fast FixesNeed a quick fix or step-by-step solution? Browse our fast answers on HowTo.KandZ.me:
Script Headers
| Pattern | Effect |
|---|
#!/bin/bash | Shebang, Bash interpreter |
#!/usr/bin/env bash | Portable shebang |
set -e | Exit on failing command |
set -u | Exit on unset variable |
set -o pipefail | Pipeline fails on any stage failure |
set -euo pipefail | Strict mode (all three) |
set -x | Trace commands to stderr |
set +x | Disable tracing |
IFS=$'\n\t' | Safer word splitting |
Variables
| Syntax | Purpose |
|---|
var=value | Assign (no spaces around =) |
local var=value | Function-local variable |
readonly var=value | Immutable variable |
export var=value | Export to child processes |
${var} | Expand variable |
${var:-default} | Default if unset/empty |
${var-default} | Default if unset |
${var:=default} | Assign default if unset |
${var:?message} | Error if unset |
${var:+alt} | Alt if set |
${#var} | Length |
${var:offset:length} | Substring |
${var#pattern} | Remove shortest prefix |
${var##pattern} | Remove longest prefix |
${var%pattern} | Remove shortest suffix |
${var%%pattern} | Remove longest suffix |
${var/old/new} | Replace first match |
${var//old/new} | Replace all matches |
${var^^} | Uppercase |
${var,,} | Lowercase |
Special Variables
| Variable | Value |
|---|
$0 | Script name |
$1โ$9 | Positional arguments |
${10} | Tenth argument and beyond |
$# | Argument count |
$@ | All arguments (quoted = separate words) |
$* | All arguments (quoted = one word) |
$? | Last exit status |
$$ | Shell PID |
$BASHPID | Current Bash PID (subshell-aware) |
$! | Last background PID |
$LINENO | Current line number |
$BASH_COMMAND | Command being executed |
$FUNCNAME | Current function name |
$RANDOM | Random 0โ32767 |
$SECONDS | Seconds since shell started |
$PIPESTATUS | Array of pipeline exit codes |
Conditionals
| Syntax | Meaning |
|---|
[[ -f file ]] | Regular file exists |
[[ -d dir ]] | Directory exists |
[[ -e path ]] | Anything exists |
[[ -L path ]] | Symbolic link |
[[ -r file ]] | Readable |
[[ -w file ]] | Writable |
[[ -x file ]] | Executable |
[[ -s file ]] | Non-empty |
[[ -O file ]] | Owned by user |
[[ -G file ]] | Owned by group |
[[ -N file ]] | Modified since read |
[[ $a -eq $b ]] | Numeric equal |
[[ $a -ne $b ]] | Numeric not equal |
[[ $a -lt $b ]] | Numeric less than |
[[ $a -gt $b ]] | Numeric greater than |
[[ $a -le $b ]] | Numeric less or equal |
[[ $a -ge $b ]] | Numeric greater or equal |
[[ $a == $b ]] | String equal (pattern match) |
[[ $a != $b ]] | String not equal |
[[ $a < $b ]] | String less than (lexical) |
[[ $a > $b ]] | String greater than |
[[ $a =~ regex ]] | Regex match |
[[ -z $a ]] | Empty string |
[[ -n $a ]] | Non-empty string |
[[ $a && $b ]] | Logical AND |
[[ $a || $b ]] | Logical OR |
[[ ! $a ]] | Logical NOT |
String Comparison vs Numeric
| Type | Operators |
|---|
| String | =, !=, <, >, -z, -n |
| Numeric | -eq, -ne, -lt, -le, -gt, -ge |
| Arithmetic | (( )) for all math |
Arithmetic
| Syntax | Purpose |
|---|
$((a + b)) | Addition |
$((a - b)) | Subtraction |
$((a * b)) | Multiplication |
$((a / b)) | Integer division |
$((a % b)) | Modulo |
$((a ** b)) | Exponentiation |
((a++)) | Increment |
((a--)) | Decrement |
((a += 5)) | Compound assignment |
let "a = 1 + 2" | Alternative syntax |
Loops
| Pattern | Purpose |
|---|
for i in 1 2 3; do ...; done | List iteration |
for ((i=0; i<10; i++)); do ...; done | C-style loop |
for i in {1..10}; do ...; done | Brace range |
for f in *.txt; do ...; done | Glob iteration |
for ((i=0; i<${#arr[@]}; i++)); do ...; done | Array by index |
while [[ $i -lt 10 ]]; do ...; done | While loop |
while read -r line; do ...; done < file | Read file line by line |
until [[ $i -ge 10 ]]; do ...; done | Until loop |
break | Exit loop |
continue | Skip to next iteration |
break 2 | Exit two nested loops |
Arrays
| Syntax | Purpose |
|---|
arr=() | Empty array |
arr=(a b c) | Initialize |
arr+=(d) | Append |
${arr[0]} | First element |
${arr[-1]} | Last element |
${arr[@]} | All elements (separate) |
${arr[*]} | All elements (joined) |
${#arr[@]} | Element count |
${!arr[@]} | All indices |
${arr[@]:1:2} | Slice (offset 1, length 2) |
unset arr[1] | Remove element |
declare -A map | Associative array |
map[key]=value | Set key |
${map[key]} | Get key |
${!map[@]} | All keys |
${map[@]} | All values |
Functions
| Syntax | Purpose |
|---|
name() { ...; } | Define function |
function name { ...; } | Alternative syntax |
local var=value | Local variable |
return N | Return status (0โ255) |
$1, $@, $# | Function arguments |
${FUNCNAME[0]} | Current function name |
name arg1 arg2 | Call function |
Pipelines and Redirection
| Syntax | Purpose |
|---|
cmd > file | Redirect stdout (overwrite) |
cmd >> file | Redirect stdout (append) |
cmd 2> file | Redirect stderr |
cmd &> file | Redirect both |
cmd 2>&1 | Merge stderr into stdout |
cmd < file | Redirect stdin |
cmd <<< "string" | Here-string |
cmd <<EOF ... EOF | Here-document |
cmd1 | cmd2 | Pipe stdout to stdin |
cmd1 |& cmd2 | Pipe stdout+stderr |
cmd >(other) | Process substitution (output) |
cmd <(other) | Process substitution (input) |
tee file | Write to file and stdout |
exec 3> file | Open FD 3 for writing |
exec 3>&- | Close FD 3 |
Job Control
| Command | Purpose |
|---|
cmd & | Run in background |
jobs | List jobs |
jobs -l | List with PIDs |
fg %1 | Foreground job 1 |
bg %1 | Background job 1 |
Ctrl+Z | Suspend foreground job |
kill %1 | Kill job by number |
kill $pid | Kill by PID |
kill -9 $pid | SIGKILL |
kill -0 $pid | Check liveness |
wait | Wait for all background jobs |
wait $pid | Wait for specific PID |
disown | Detach from job table |
nohup cmd & | Ignore SIGHUP |
Signals and Traps
| Signal | Number | Meaning |
|---|
SIGHUP | 1 | Terminal closed |
SIGINT | 2 | Ctrl+C |
SIGQUIT | 3 | Ctrl+\ |
SIGKILL | 9 | Forced kill (uncatchable) |
SIGTERM | 15 | Polite termination |
SIGTSTP | 20 | Ctrl+Z |
SIGCONT | 18 | Resume |
EXIT | โ | Shell exits |
ERR | โ | set -e failure |
DEBUG | โ | Before each command |
Trap Patterns
| Pattern | Purpose |
|---|
trap 'cleanup' EXIT | Run cleanup on any exit |
trap 'echo interrupted; exit 130' INT | Handle Ctrl+C |
trap 'echo terminated; exit 143' TERM | Handle SIGTERM |
trap 'echo error line $LINENO' ERR | Report failures |
trap - INT | Reset to default |
trap -p | Show registered traps |
trap -l | List signal names |
Text Processing
| Command | Purpose |
|---|
grep pattern file | Search lines |
grep -E 'regex' file | Extended regex |
grep -c | Count matches |
grep -v | Invert match |
grep -i | Case-insensitive |
grep -o | Output only match |
sed 's/old/new/' file | Replace first per line |
sed 's/old/new/g' | Replace all |
sed -i | Edit in place |
sed -n '5,10p' | Print lines 5โ10 |
awk '{print $1}' | Print first field |
awk -F: '{print $1}' | Custom delimiter |
awk '$3 > 100' | Filter by field |
cut -d: -f1 | Cut field |
sort file | Sort lines |
sort -n | Numeric sort |
sort -u | Unique sort |
uniq | Remove adjacent duplicates |
uniq -c | Count occurrences |
tr 'a-z' 'A-Z' | Translate characters |
tr -d '\n' | Delete characters |
head -n 10 | First 10 lines |
tail -n 10 | Last 10 lines |
tail -f | Follow file |
wc -l | Count lines |
wc -w | Count words |
wc -c | Count bytes |
xargs | Build command from stdin |
Regular Expressions
| Pattern | Meaning |
|---|
. | Any character |
* | Zero or more |
+ | One or more |
? | Zero or one |
^ | Start of line |
$ | End of line |
[abc] | Character class |
[^abc] | Negated class |
[a-z] | Range |
(abc) | Group |
a|b | Alternation (ERE) |
{n} | Exactly n (ERE) |
{n,m} | Between n and m (ERE) |
\d | Digit (PCRE) |
\w | Word char (PCRE) |
\s | Whitespace (PCRE) |
[[:digit:]] | POSIX digit |
[[:alpha:]] | POSIX letter |
[[:space:]] | POSIX whitespace |
Bash Regex
| Syntax | Meaning |
|---|
[[ $x =~ pattern ]] | Regex match |
[[ $x =~ $var ]] | Pattern from variable (unquoted) |
[[ $x =~ "pattern" ]] | Literal (quoted) |
${BASH_REMATCH[0]} | Full match |
${BASH_REMATCH[1]} | First group |
getopts
| Syntax | Meaning |
|---|
getopts "ab:c" opt | Parse: -a flag, -b arg, -c flag |
getopts ":ab:" opt | Silent mode (leading colon) |
$opt | Current option letter |
$OPTARG | Option argument |
$OPTIND | Next argument index |
while getopts ...; do case ...; esac; done | Standard loop |
shift $((OPTIND - 1)) | Remove parsed options |
Date and Time
| Format | Output |
|---|
%Y-%m-%d | 2026-11-05 |
%H:%M:%S | 14:30:00 |
%Y-%m-%dT%H:%M:%S%z | 2026-11-05T14:30:00+0100 |
%s | Unix epoch |
%A | Weekday name |
%B | Month name |
%j | Day of year |
date -u | UTC |
date -d "yesterday" | Relative date |
date +%s | Epoch seconds |
File Operations
| Command | Purpose |
|---|
touch file | Create or update timestamp |
mkdir -p dir | Create with parents |
cp -r src dst | Copy recursively |
mv src dst | Move/rename |
rm -rf dir | Remove recursively |
ln -s target link | Symlink |
ln target link | Hard link |
chmod 755 file | Set permissions |
chown user:group file | Set ownership |
mktemp | Temporary file |
mktemp -d | Temporary directory |
find . -name "*.log" | Find files |
find . -type f -mtime +7 | Find older files |
find . -exec cmd {} \; | Execute on results |
basename /a/b/c.txt | c.txt |
dirname /a/b/c.txt | /a/b |
realpath file | Absolute path |
Process Management
| Command | Purpose |
|---|
ps aux | List processes |
ps -ef | Alternative format |
pgrep name | Find PID by name |
pkill name | Kill by name |
top | Interactive process viewer |
htop | Better process viewer |
lsof -p pid | Open files |
ss -tlnp | Listening ports |
systemctl status svc | Service status |
systemctl restart svc | Restart service |
File Locking
| Pattern | Purpose |
|---|
flock -n file cmd | Non-blocking lock |
flock -w 10 file cmd | Wait up to 10s |
( flock -n 200 || exit 1; ... ) 200>file | In-script lock |
exec env FLOCKER="$0" flock -en "$0" "$0" "$@" | Self-locking |
SSH
| Command | Purpose |
|---|
ssh user@host cmd | Run command |
ssh -o BatchMode=yes host cmd | No prompts |
ssh -o ConnectTimeout=10 host cmd | Timeout |
ssh -o ControlMaster=yes -fN host | Master connection |
ssh -o ControlPath=sock host cmd | Reuse master |
ssh -O exit host | Close master |
ssh-keygen -t ed25519 -f key -N "" | Generate key |
ssh-copy-id -i key.pub user@host | Copy public key |
Debugging
| Command | Purpose |
|---|
set -x | Trace commands |
set +x | Stop tracing |
bash -n script.sh | Check syntax |
bash -x script.sh | Run with tracing |
shellcheck script.sh | Static analysis |
trap '...' DEBUG | Trap before each command |
declare -p var | Show variable type and value |
type cmd | Where command is defined |
command -v cmd | Find command path |
Common Patterns
| Pattern | Purpose |
|---|
cmd || true | Ignore failure |
cmd || { echo "fail"; exit 1; } | Fail with message |
[[ -d dir ]] || mkdir -p dir | Create if missing |
while read -r line; do ...; done < file | Read file |
while IFS= read -r line; do ...; done < file | Preserve whitespace |
read -p "Prompt: " var | Read user input |
read -s -p "Password: " var | Read password silently |
printf '%s\n' "${arr[@]}" | Print array |
mapfile -t arr < file | Read file into array |
exec 3>&1 | Save stdout |
exec > logfile | Redirect all output |
exec >&3 | Restore stdout |
Quick Rules
| Rule | Reason |
|---|
Quote variables: "$var" | Prevent word splitting |
Use [[ ]] over [ ] | Safer, supports regex |
Use $(...) over backticks | Nested, readable |
Use printf over echo | Portable, predictable |
Use local in functions | Prevent scope leaks |
Use set -euo pipefail | Fail fast |
Use -r with read | Prevent backslash interpretation |
Use -- to end options | Handle filenames starting with - |
| Prefer arrays over space-separated strings | Handle spaces correctly |
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!