Bash Cheat Sheet

Shell scripting and one-liners: variables, conditionals, loops, functions, job control, and string manipulation.

Core DevOps8 sections · 73 commands
⌘K

Variables

10
VAR=value

Assign a variable (no spaces)

export VAR=value

Export to child processes

echo "$VAR"

Expand the variable inside quotes

echo '$VAR'

Literal, no expansion

VAR=""; unset VAR

Clear a variable

readonly VAR=value

Make a variable immutable

read -p 'prompt> ' VAR

Read input into a variable

env

Show the environment

echo "$PATH"

Show the executable search path

export NAME=value

Set and export an environment variable

Parameter Expansion

10
"${VAR:-default}"

Use default if unset or empty

"${VAR:=default}"

Assign a default in place

"${#VAR}"

Length of the value

"${VAR:0:5}"

Substring starting at 0, 5 chars

"${VAR%.*}"

Remove shortest match from the end

"${VAR#prefix}"

Remove shortest match from the start

"${VAR^^}"

Uppercase the value

"${VAR,,}"

Lowercase the value

"${VAR//OLD/NEW}"

Replace all occurrences

"${VAR: -3}"

Last 3 characters (note the space)

Quoting & Pipes

10
CMD1 | CMD2

Pipe stdout into the next command

CMD1 | tee FILE

Output to stdout and a file at once

CMD >FILE 2>&1

Redirect stdout and stderr to a file

CMD &>/dev/null

Discard both streams (bash 4+)

CMD |& less

Pipe both streams (bash 4+)

CMD $(cmd)

Command substitution (new-style)

CMD `cmd`

Command substitution (old-style)

echo "$(date +%s)"

Current Unix timestamp

a=$(cat FILE)

Capture file content in a variable

<(CMD)

Process substitution (treat as a file)

Conditionals

10
if [ -f FILE ]; then CMD; fi

Run if the file exists

if [ "$A" = "$B" ]; then CMD; fi

String equality

if [ "$A" -gt 10 ]; then CMD; fi

Numeric greater-than

if [ -n "$VAR" ]; then CMD; fi

True if the variable is non-empty

if [ -z "$VAR" ]; then CMD; fi

True if the variable is empty

if [ -d DIR ]; then CMD; fi

True if DIR exists and is a directory

if CMD; then CMD; else CMD; fi

Branch on a command's exit status

case "$1" in start) CMD;; stop) CMD;; *) echo '?'; esac

Switch on a value

[[ ARCH == *.gz ]] && CMD || CMD2

Extended pattern match, ternary style

[ "$A" = "$B" ] && echo y

One-line guard

Loops

8
for i in 1 2 3; do echo $i; done

Loop over literal values

for f in *.log; do gzip "$f"; done

Loop over matching files

for ((i=0; i<10; i++)); do CMD; done

C-style numeric loop

while read -r line; do echo "$line"; done < FILE

Read a file line by line

until ping -c1 HOST; do sleep 2; done

Loop until success

for f in $(find DIR -name '*.conf'); do CMD; done

Loop over command output

for i in {1..5}; do CMD; done

Range expansion

true && CMD || (echo 'failed' >&2; exit 1)

Bail early on failure

Functions

6
greet() { echo "hello $1"; }

Define a function with args

die() { echo "$1" >&2; exit 1; }

Error-and-exit helper

function f { return 1; }

Return a status from a function

Trap 'cleanup' EXIT

Run cleanup on script exit

trap 'kill $PID' TERM INT

Forward signals to a child

export -f fname

Export a function to subshells

Job Control & Background

9
CMD &

Run in the background

CMD & echo $!

Background and print its PID

jobs -l

List background jobs with PIDs

fg %1

Bring job 1 to the foreground

bg %1

Resume job 1 in the background

wait $PID

Wait for a background PID to finish

Ctrl+Z

Suspend the foreground job

wait

Wait for all background jobs

set -euo pipefail

Strict mode: exit on error or unset var

History & Shortcuts

10
history

Show command history

!!

Last command

!$

Last argument of the last command

^old^new

Rerun last command with a substitution

Ctrl+R

Reverse-search history

Ctrl+C

Stop the current command

Ctrl+D

Exit shell / send EOF

Ctrl+L

Clear the terminal

fc -l -5

Show the last 5 commands

HISTCONTROL=ignoreboth

Ignore duplicates and leading spaces