1#!/usr/bin/env bash2set -euo pipefail3 4log() { printf '[%s] %s\n' "$(date +%T)" "$*" >&2; }5die() { log "ERROR: $*"; exit 1; }6usage() { echo "usage: ${0##*/} [-v] ARG" >&2; exit 2; }7 8tmp=$(mktemp -d)9trap 'rm -rf "$tmp"' EXIT10 11main() {12 [[ $# -ge 1 ]] || usage13 log "starting with $1"14}15 16main "$@"
SHELLbashutf-8 · 16L
| Command | What it does |
|---|
chmod +x script.sh / ./script.sh | make executable / run |
bash script.sh | run without execute permission |
bash -n script.sh | check syntax only |
bash -x script.sh | trace every command |
shellcheck script.sh | lint for common bugs |
source file / . file | run in the current shell |
echo $? | exit code of the last command |
| Syntax | What it does |
|---|
name=value | assign (no spaces around =) |
"$name" / "${name}" | use it; always quote |
${name}_suffix | braces mark where the name ends |
$(command) | command output |
$((a + b * 2)) | integer arithmetic |
'literal $text' | no expansion |
export NAME | pass to child programs |
VAR=x ./script.sh | set for one command |
readonly NAME=value / unset name | constant / delete |
$HOME $USER $PATH $PWD $RANDOM $SECONDS | useful built-ins |
| Syntax | What it does |
|---|
$0 $1 $2 ${10} | script name and arguments |
$# / "$@" | how many / all, safely |
shift | drop $1 |
${1:-default} | default value |
${1:?message} | required, exit with message |
read -r -p "Question? " answer | ask the user |
while getopts ":ve:h" opt; do … done; shift $((OPTIND - 1)) | parse options |
| Syntax | Result (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 |
| Syntax | True when |
|---|
if cmd; then …; elif …; else …; fi | branch 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 -ge | numbers |
(( n > 5 )) | arithmetic test |
-e -f -d -s -r -w -x FILE | exists, file, dir, not empty, readable, writable, executable |
a -nt b | a newer than b |
&& || ! inside [[ ]] | and, or, not |
cmd && next / cmd || fallback | on success / on failure |
case $x in a|b) … ;; *) … ;; esac | one value, many patterns |
Exit codes: 0 success, 1 error, 2 usage, 126 not executable, 127 not found, 130 Ctrl+C.
| Syntax | What it does |
|---|
for x in a b c; do …; done | over words |
for f in /var/log/*.log; do …; done | over files (safe with spaces) |
for n in {1..10}; do …; done | range |
for ((i=0; i<5; i++)); do …; done | counter |
while cmd; do …; done / until cmd; do …; done | while / until a command succeeds |
while IFS= read -r line; do …; done < file | lines of a file |
while IFS=, read -r a b c; do …; done < f.csv | CSV fields |
while read -r l; do …; done < <(cmd) | command output, variables survive |
continue / break | next item / leave loop |
| Syntax | What it does |
|---|
name() { …; } | define (before use) |
name arg1 arg2 | call; inside: $1 $2 $# "$@" |
local var=value | variable visible only inside |
return N | exit code 0–255 |
result=$(name args) | capture output |
echo "msg" >&2 | log without polluting output |
main "$@" | structure larger scripts |
| Syntax | What 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 |
| Syntax | What it does |
|---|
> f / >> f | stdout overwrite / append |
2> f / > f 2>&1 / &> f | stderr / both / both |
> /dev/null 2>&1 | silence |
< f | file as stdin |
a | b / a |& b | pipe stdout / both |
cmd | tee -a f | save and show |
cat <<EOF … EOF / <<'EOF' | here-document / literal |
cmd <<< "$s" | here-string |
{ a; b; } > f | group output |
diff <(cmd1) <(cmd2) | process substitution |
Text processing
| Command | What it does |
|---|
grep -rn "x" dir / grep -E 'a|b' / grep -v / grep -c / grep -o | search |
cut -d, -f1,3 | fields |
sort -n -r -k2 -t, / sort -u | sort |
uniq -c | count 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.bak | edit |
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 8 | per line / parallel |
wc -l / head -n / tail -n / column -t | count / first / last / align |
| Syntax | What it does |
|---|
set -e | exit on the first failure |
set -u | unset variables are errors |
set -o pipefail | a failure anywhere in a pipe counts |
cmd || die "msg" | explicit check |
trap cleanup EXIT | always run cleanup |
trap 'echo "line $LINENO: $BASH_COMMAND" >&2' ERR | report failures |
tmp=$(mktemp) / mktemp -d | safe temp file / folder |
exec 9>/var/lock/x.lock; flock -n 9 || exit 0 | single instance |
local out; out=$(cmd) | keep failures visible (not local out=$(cmd)) |
| Command | What it does |
|---|
bash -x script.sh / set -x … set +x | trace all / a section |
PS4='+ ${BASH_SOURCE}:${LINENO}: ' | trace with file and line |
declare -p var | exact value and type |
shellcheck -f gcc *.sh | lint, one line per issue |
# shellcheck disable=SC2086 | silence one line, with a reason |
file script.sh | detect CRLF line endings |
| Item | What it does |
|---|
crontab -e | edit cron jobs |
m h dom mon dow cmd | the five fields |
*/15 * * * * / 0 2 * * * / 0 9 * * 1-5 | every 15 min / daily 02:00 / weekdays 09:00 |
cmd >> /var/log/x.log 2>&1 | always capture output |
flock -n /tmp/x.lock cmd | never overlap |
systemctl list-timers / OnCalendar= / Persistent=true | systemd timers |
| Bash | POSIX 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 -e | printf |
| Bats | What it does |
|---|
@test "name" { … } | a test |
run cmd args | capture $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.