Skip to content
$ lynuxpro
← Bash Scripting

CHEAT SHEET · 17 LESSONS IN ONE PAGE

Bash scripting cheat sheet

Variables, quoting, conditions, loops, functions, arrays, text tools, error handling and the script template, on one page.

Saves a clean, printable copy (Ctrl+P or ⌘P also works).

Script template

#!/usr/bin/env bashset -euo pipefail log() { printf '[%s] %s\n' "$(date +%T)" "$*" >&2; }die() { log "ERROR: $*"; exit 1; }usage() { echo "usage: ${0##*/} [-v] ARG" >&2; exit 2; } tmp=$(mktemp -d)trap 'rm -rf "$tmp"' EXIT main() {  [[ $# -ge 1 ]] || usage  log "starting with $1"} main "$@"
SHELLbashutf-8 · 16L

Running scripts

CommandWhat it does
chmod +x script.sh / ./script.shmake executable / run
bash script.shrun without execute permission
bash -n script.shcheck syntax only
bash -x script.shtrace every command
shellcheck script.shlint for common bugs
source file / . filerun in the current shell
echo $?exit code of the last command

Variables and quoting

SyntaxWhat it does
name=valueassign (no spaces around =)
"$name" / "${name}"use it; always quote
${name}_suffixbraces mark where the name ends
$(command)command output
$((a + b * 2))integer arithmetic
'literal $text'no expansion
export NAMEpass to child programs
VAR=x ./script.shset for one command
readonly NAME=value / unset nameconstant / delete
$HOME $USER $PATH $PWD $RANDOM $SECONDSuseful built-ins

Arguments and input

SyntaxWhat it does
$0 $1 $2 ${10}script name and arguments
$# / "$@"how many / all, safely
shiftdrop $1
${1:-default}default value
${1:?message}required, exit with message
read -r -p "Question? " answerask the user
while getopts ":ve:h" opt; do … done; shift $((OPTIND - 1))parse options

Parameter expansion

SyntaxResult (for f=/var/log/app.tar.gz)
${#f}length
${f##*/}app.tar.gz (basename)
${f%/*}/var/log (dirname)
${f%.gz} / ${f%%.*}/var/log/app.tar / /var/log/app
${f#*.}tar.gz
${f/log/data} / ${f//a/A}replace first / all
${f:0:4}substring
${v^^} / ${v,,} / ${v^}upper / lower / capitalise
${v:-x} ${v:=x} ${v:?msg} ${v:+x}default / assign default / require / alternate
${!name} / ${!prefix*}indirection / variable names

Conditions

SyntaxTrue when
if cmd; then …; elif …; else …; fibranch on a command's exit code
[[ $a == "$b" ]] / !=strings equal / differ
[[ $a == pre* ]]pattern match
[[ $s =~ ^v([0-9]+)$ ]]regex; groups in BASH_REMATCH
[[ -z $a ]] / [[ -n $a ]]empty / not empty
-eq -ne -lt -le -gt -genumbers
(( n > 5 ))arithmetic test
-e -f -d -s -r -w -x FILEexists, file, dir, not empty, readable, writable, executable
a -nt ba newer than b
&& || ! inside [[ ]]and, or, not
cmd && next / cmd || fallbackon success / on failure
case $x in a|b) … ;; *) … ;; esacone value, many patterns

Exit codes: 0 success, 1 error, 2 usage, 126 not executable, 127 not found, 130 Ctrl+C.

Loops

SyntaxWhat it does
for x in a b c; do …; doneover words
for f in /var/log/*.log; do …; doneover files (safe with spaces)
for n in {1..10}; do …; donerange
for ((i=0; i<5; i++)); do …; donecounter
while cmd; do …; done / until cmd; do …; donewhile / until a command succeeds
while IFS= read -r line; do …; done < filelines of a file
while IFS=, read -r a b c; do …; done < f.csvCSV fields
while read -r l; do …; done < <(cmd)command output, variables survive
continue / breaknext item / leave loop

Functions

SyntaxWhat it does
name() { …; }define (before use)
name arg1 arg2call; inside: $1 $2 $# "$@"
local var=valuevariable visible only inside
return Nexit code 0–255
result=$(name args)capture output
echo "msg" >&2log without polluting output
main "$@"structure larger scripts

Arrays

SyntaxWhat it does
a=(x y z) / a+=(w)create / append
${a[0]} / ${a[-1]}first / last
"${a[@]}" / ${#a[@]}all elements / count
${!a[@]}indexes
${a[@]:1:2}slice
mapfile -t a < <(cmd)lines into an array
declare -A m=([k]=v) / ${m[k]} / ${!m[@]}associative array / value / keys
[[ -v m[k] ]]key exists

Redirection

SyntaxWhat it does
> f / >> fstdout overwrite / append
2> f / > f 2>&1 / &> fstderr / both / both
> /dev/null 2>&1silence
< ffile as stdin
a | b / a |& bpipe stdout / both
cmd | tee -a fsave and show
cat <<EOF … EOF / <<'EOF'here-document / literal
cmd <<< "$s"here-string
{ a; b; } > fgroup output
diff <(cmd1) <(cmd2)process substitution

Text processing

CommandWhat it does
grep -rn "x" dir / grep -E 'a|b' / grep -v / grep -c / grep -osearch
cut -d, -f1,3fields
sort -n -r -k2 -t, / sort -usort
uniq -ccount duplicates (after sort)
tr 'a-z' 'A-Z' / tr -d '\r'translate / delete
sed 's/a/b/g' / sed -n '5,10p' / sed '/re/d' / sed -i.bakedit
awk '{print $1, $NF}' / awk -F: '$3>=1000'fields, filters
awk '{s+=$2} END {print s}'sum a column
awk -v x="$var" '$2 == x'pass a shell variable
jq -r '.items[].name'JSON
xargs -I{} cmd {} / xargs -P 8per line / parallel
wc -l / head -n / tail -n / column -tcount / first / last / align

Error handling

SyntaxWhat it does
set -eexit on the first failure
set -uunset variables are errors
set -o pipefaila failure anywhere in a pipe counts
cmd || die "msg"explicit check
trap cleanup EXITalways run cleanup
trap 'echo "line $LINENO: $BASH_COMMAND" >&2' ERRreport failures
tmp=$(mktemp) / mktemp -dsafe temp file / folder
exec 9>/var/lock/x.lock; flock -n 9 || exit 0single instance
local out; out=$(cmd)keep failures visible (not local out=$(cmd))

Debugging

CommandWhat it does
bash -x script.sh / set -x … set +xtrace all / a section
PS4='+ ${BASH_SOURCE}:${LINENO}: 'trace with file and line
declare -p varexact value and type
shellcheck -f gcc *.shlint, one line per issue
# shellcheck disable=SC2086silence one line, with a reason
file script.shdetect CRLF line endings

Scheduling

ItemWhat it does
crontab -eedit cron jobs
m h dom mon dow cmdthe five fields
*/15 * * * * / 0 2 * * * / 0 9 * * 1-5every 15 min / daily 02:00 / weekdays 09:00
cmd >> /var/log/x.log 2>&1always capture output
flock -n /tmp/x.lock cmdnever overlap
systemctl list-timers / OnCalendar= / Persistent=truesystemd timers

Portable sh and testing

BashPOSIX sh
[[ $a == $b ]][ "$a" = "$b" ]
arr=(a b)set -- a b and "$@"
${v//a/b}printf '%s' "$v" | sed 's/a/b/g'
source f. f
echo -eprintf
BatsWhat it does
@test "name" { … }a test
run cmd argscapture $status, $output, ${lines[@]}
[ "$status" -eq 0 ] / [ "$output" = "x" ]assertions
setup() / teardown()before / after each test
bats test/run all tests

Get every new cheat sheet by email

We're adding cheat sheets for Terraform, AWS, GitLab CI/CD and more.

One email a week at most. Unsubscribe with one click.