Bash Variables, Quoting, and Expansion

Bash variables, parameter expansion, quoting rules, command substitution, arithmetic, and shell expansion patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Variables
Assign variable
name='Jonathan'

# Assign a shell variable.

Read variable
echo "$name"

# Expand a variable with double quotes.

Export variable
export APP_ENV=production

# Export a variable to child processes.

Unset variable
unset name

# Remove a variable definition.

Default value expansion
echo "${PORT:-3000}"

# Use a fallback if variable is unset or empty.

Assign default value
echo "${PORT:=3000}"

# Assign default if variable is unset or empty.

Require variable
echo "${DATABASE_URL:?DATABASE_URL is required}"

# Abort expansion with error if variable is missing.

Alternate value expansion
echo "${DEBUG:+enabled}"

# Use alternate text when variable is set and non-empty.

## Quoting
Literal single-quoted string
echo 'Path is $HOME'

# Single quotes prevent all expansion.

Expandable double-quoted string
echo "Path is $HOME"

# Double quotes allow variable and command expansion.

Escape one character
echo "A quote: \""

# Backslash escapes the next character in many contexts.

ANSI-C quoted string
printf '%s
' $'line1
line2'

# Use ANSI-C quoting for escapes like newline and tab.

Print literal dollar sign
echo '\$HOME'

# Print shell metacharacters literally.

## Parameter and Command Expansion
Command substitution
today=$(date +%F)

# Capture command output into a variable.

Arithmetic expansion
echo $((2 + 3 * 4))

# Evaluate an arithmetic expression.

String length
echo "${#name}"

# Get length of a variable's value.

Substring expansion
echo "${name:0:4}"

# Extract a substring by offset and length.

Replace first match
echo "${file/.txt/.bak}"

# Replace first matching substring.

Replace all matches
echo "${path//\//:}"

# Replace all matching substrings.

Remove shortest prefix
echo "${path#*/}"

# Strip shortest matching prefix pattern.

Remove longest suffix
echo "${file%%.*}"

# Strip the longest matching suffix pattern.

## Globbing and Brace Expansion
Match files with glob
printf '%s
' *.txt

# Expand a glob to matching files.

Brace expansion
printf '%s
' file-{a,b,c}.txt

# Generate multiple words from a brace expression.

Sequence expansion
printf '%s
' {1..5}

# Generate a numeric sequence.

Enable nullglob
shopt -s nullglob

# Expand unmatched globs to nothing.

Include dotfiles in globs
shopt -s dotglob

# Make globs match dotfiles too.