| |

Bash Scripting 31 ๐Ÿง Cheatsheet โ€” Quick Reference

โฑ๏ธ 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.


Script Headers

PatternEffect
#!/bin/bashShebang, Bash interpreter
#!/usr/bin/env bashPortable shebang
set -eExit on failing command
set -uExit on unset variable
set -o pipefailPipeline fails on any stage failure
set -euo pipefailStrict mode (all three)
set -xTrace commands to stderr
set +xDisable tracing
IFS=$'\n\t'Safer word splitting

Variables

SyntaxPurpose
var=valueAssign (no spaces around =)
local var=valueFunction-local variable
readonly var=valueImmutable variable
export var=valueExport 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

VariableValue
$0Script name
$1โ€“$9Positional arguments
${10}Tenth argument and beyond
$#Argument count
$@All arguments (quoted = separate words)
$*All arguments (quoted = one word)
$?Last exit status
$$Shell PID
$BASHPIDCurrent Bash PID (subshell-aware)
$!Last background PID
$LINENOCurrent line number
$BASH_COMMANDCommand being executed
$FUNCNAMECurrent function name
$RANDOMRandom 0โ€“32767
$SECONDSSeconds since shell started
$PIPESTATUSArray of pipeline exit codes

Conditionals

SyntaxMeaning
[[ -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

TypeOperators
String=, !=, <, >, -z, -n
Numeric-eq, -ne, -lt, -le, -gt, -ge
Arithmetic(( )) for all math

Arithmetic

SyntaxPurpose
$((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

PatternPurpose
for i in 1 2 3; do ...; doneList iteration
for ((i=0; i<10; i++)); do ...; doneC-style loop
for i in {1..10}; do ...; doneBrace range
for f in *.txt; do ...; doneGlob iteration
for ((i=0; i<${#arr[@]}; i++)); do ...; doneArray by index
while [[ $i -lt 10 ]]; do ...; doneWhile loop
while read -r line; do ...; done < fileRead file line by line
until [[ $i -ge 10 ]]; do ...; doneUntil loop
breakExit loop
continueSkip to next iteration
break 2Exit two nested loops

Arrays

SyntaxPurpose
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 mapAssociative array
map[key]=valueSet key
${map[key]}Get key
${!map[@]}All keys
${map[@]}All values

Functions

SyntaxPurpose
name() { ...; }Define function
function name { ...; }Alternative syntax
local var=valueLocal variable
return NReturn status (0โ€“255)
$1, $@, $#Function arguments
${FUNCNAME[0]}Current function name
name arg1 arg2Call function

Pipelines and Redirection

SyntaxPurpose
cmd > fileRedirect stdout (overwrite)
cmd >> fileRedirect stdout (append)
cmd 2> fileRedirect stderr
cmd &> fileRedirect both
cmd 2>&1Merge stderr into stdout
cmd < fileRedirect stdin
cmd <<< "string"Here-string
cmd <<EOF ... EOFHere-document
cmd1 | cmd2Pipe stdout to stdin
cmd1 |& cmd2Pipe stdout+stderr
cmd >(other)Process substitution (output)
cmd <(other)Process substitution (input)
tee fileWrite to file and stdout
exec 3> fileOpen FD 3 for writing
exec 3>&-Close FD 3

Job Control

CommandPurpose
cmd &Run in background
jobsList jobs
jobs -lList with PIDs
fg %1Foreground job 1
bg %1Background job 1
Ctrl+ZSuspend foreground job
kill %1Kill job by number
kill $pidKill by PID
kill -9 $pidSIGKILL
kill -0 $pidCheck liveness
waitWait for all background jobs
wait $pidWait for specific PID
disownDetach from job table
nohup cmd &Ignore SIGHUP

Signals and Traps

SignalNumberMeaning
SIGHUP1Terminal closed
SIGINT2Ctrl+C
SIGQUIT3Ctrl+\
SIGKILL9Forced kill (uncatchable)
SIGTERM15Polite termination
SIGTSTP20Ctrl+Z
SIGCONT18Resume
EXITโ€”Shell exits
ERRโ€”set -e failure
DEBUGโ€”Before each command

Trap Patterns

PatternPurpose
trap 'cleanup' EXITRun cleanup on any exit
trap 'echo interrupted; exit 130' INTHandle Ctrl+C
trap 'echo terminated; exit 143' TERMHandle SIGTERM
trap 'echo error line $LINENO' ERRReport failures
trap - INTReset to default
trap -pShow registered traps
trap -lList signal names

Text Processing

CommandPurpose
grep pattern fileSearch lines
grep -E 'regex' fileExtended regex
grep -cCount matches
grep -vInvert match
grep -iCase-insensitive
grep -oOutput only match
sed 's/old/new/' fileReplace first per line
sed 's/old/new/g'Replace all
sed -iEdit 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: -f1Cut field
sort fileSort lines
sort -nNumeric sort
sort -uUnique sort
uniqRemove adjacent duplicates
uniq -cCount occurrences
tr 'a-z' 'A-Z'Translate characters
tr -d '\n'Delete characters
head -n 10First 10 lines
tail -n 10Last 10 lines
tail -fFollow file
wc -lCount lines
wc -wCount words
wc -cCount bytes
xargsBuild command from stdin

Regular Expressions

PatternMeaning
.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|bAlternation (ERE)
{n}Exactly n (ERE)
{n,m}Between n and m (ERE)
\dDigit (PCRE)
\wWord char (PCRE)
\sWhitespace (PCRE)
[[:digit:]]POSIX digit
[[:alpha:]]POSIX letter
[[:space:]]POSIX whitespace

Bash Regex

SyntaxMeaning
[[ $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

SyntaxMeaning
getopts "ab:c" optParse: -a flag, -b arg, -c flag
getopts ":ab:" optSilent mode (leading colon)
$optCurrent option letter
$OPTARGOption argument
$OPTINDNext argument index
while getopts ...; do case ...; esac; doneStandard loop
shift $((OPTIND - 1))Remove parsed options

Date and Time

FormatOutput
%Y-%m-%d2026-11-05
%H:%M:%S14:30:00
%Y-%m-%dT%H:%M:%S%z2026-11-05T14:30:00+0100
%sUnix epoch
%AWeekday name
%BMonth name
%jDay of year
date -uUTC
date -d "yesterday"Relative date
date +%sEpoch seconds

File Operations

CommandPurpose
touch fileCreate or update timestamp
mkdir -p dirCreate with parents
cp -r src dstCopy recursively
mv src dstMove/rename
rm -rf dirRemove recursively
ln -s target linkSymlink
ln target linkHard link
chmod 755 fileSet permissions
chown user:group fileSet ownership
mktempTemporary file
mktemp -dTemporary directory
find . -name "*.log"Find files
find . -type f -mtime +7Find older files
find . -exec cmd {} \;Execute on results
basename /a/b/c.txtc.txt
dirname /a/b/c.txt/a/b
realpath fileAbsolute path

Process Management

CommandPurpose
ps auxList processes
ps -efAlternative format
pgrep nameFind PID by name
pkill nameKill by name
topInteractive process viewer
htopBetter process viewer
lsof -p pidOpen files
ss -tlnpListening ports
systemctl status svcService status
systemctl restart svcRestart service

File Locking

PatternPurpose
flock -n file cmdNon-blocking lock
flock -w 10 file cmdWait up to 10s
( flock -n 200 || exit 1; ... ) 200>fileIn-script lock
exec env FLOCKER="$0" flock -en "$0" "$0" "$@"Self-locking

SSH

CommandPurpose
ssh user@host cmdRun command
ssh -o BatchMode=yes host cmdNo prompts
ssh -o ConnectTimeout=10 host cmdTimeout
ssh -o ControlMaster=yes -fN hostMaster connection
ssh -o ControlPath=sock host cmdReuse master
ssh -O exit hostClose master
ssh-keygen -t ed25519 -f key -N ""Generate key
ssh-copy-id -i key.pub user@hostCopy public key

Debugging

CommandPurpose
set -xTrace commands
set +xStop tracing
bash -n script.shCheck syntax
bash -x script.shRun with tracing
shellcheck script.shStatic analysis
trap '...' DEBUGTrap before each command
declare -p varShow variable type and value
type cmdWhere command is defined
command -v cmdFind command path

Common Patterns

PatternPurpose
cmd || trueIgnore failure
cmd || { echo "fail"; exit 1; }Fail with message
[[ -d dir ]] || mkdir -p dirCreate if missing
while read -r line; do ...; done < fileRead file
while IFS= read -r line; do ...; done < filePreserve whitespace
read -p "Prompt: " varRead user input
read -s -p "Password: " varRead password silently
printf '%s\n' "${arr[@]}"Print array
mapfile -t arr < fileRead file into array
exec 3>&1Save stdout
exec > logfileRedirect all output
exec >&3Restore stdout

Quick Rules

RuleReason
Quote variables: "$var"Prevent word splitting
Use [[ ]] over [ ]Safer, supports regex
Use $(...) over backticksNested, readable
Use printf over echoPortable, predictable
Use local in functionsPrevent scope leaks
Use set -euo pipefailFail fast
Use -r with readPrevent backslash interpretation
Use -- to end optionsHandle filenames starting with -
Prefer arrays over space-separated stringsHandle spaces correctly

Was this helpful?


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!