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, export, inspect, and unset variables.

Assign variable

Assign a shell variable.

bashANYvariablesassignment
bash
name='Jonathan'

Do not put spaces around = in shell assignment.

Read variable

Expand a variable with double quotes.

bashANYvariablesquotes
bash
echo "$name"

Double quotes preserve spaces and most characters.

Export variable

Export a variable to child processes.

bashANYexportenv
bash
export APP_ENV=production

Needed when subprocesses should receive the value.

Unset variable

Remove a variable definition.

bashANYunsetvariables
bash
unset name

Useful for cleanup and testing default expansion behavior.

Default value expansion

Use a fallback if variable is unset or empty.

bashANYparameter-expansiondefaults
bash
echo "${PORT:-3000}"

One of the most common parameter expansion patterns.

Assign default value

Assign default if variable is unset or empty.

bashANYparameter-expansiondefaults
bash
echo "${PORT:=3000}"

Be careful because this mutates the variable.

Require variable

Abort expansion with error if variable is missing.

bashANYparameter-expansionvalidation
bash
echo "${DATABASE_URL:?DATABASE_URL is required}"

Great for defensive scripts and deployment checks.

Alternate value expansion

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

bashANYparameter-expansionconditional
bash
echo "${DEBUG:+enabled}"

Good for optional flags and output labels.

Quoting

Single quotes, double quotes, escaping, and ANSI-C quoting.

Literal single-quoted string

Single quotes prevent all expansion.

bashANYquotesliteral
bash
echo 'Path is $HOME'

Use when you need literal shell characters.

Expandable double-quoted string

Double quotes allow variable and command expansion.

bashANYquotesexpansion
bash
echo "Path is $HOME"

Usually the safest choice around variable expansions.

Escape one character

Backslash escapes the next character in many contexts.

bashANYquotesescape
bash
echo "A quote: \""

Needed when embedding quotes in strings.

ANSI-C quoted string

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

bashANYquotesansi-c
bash
printf '%s
' $'line1
line2'

Bash supports $'...' expansion for escaped literals.

Print literal dollar sign

Print shell metacharacters literally.

bashANYquotesliteral
bash
echo '\$HOME'

Handy when writing examples or templates.

Parameter and Command Expansion

Substring, replacement, command substitution, and arithmetic.

Command substitution

Capture command output into a variable.

bashANYsubstitutioncommands
bash
today=$(date +%F)

Prefer $(...) over backticks for clarity and nesting.

Arithmetic expansion

Evaluate an arithmetic expression.

bashANYarithmeticexpansion
bash
echo $((2 + 3 * 4))

Useful for counters, lengths, and simple math.

String length

Get length of a variable's value.

bashANYlengthstrings
bash
echo "${#name}"

Works for strings and arrays.

Substring expansion

Extract a substring by offset and length.

bashANYsubstringstrings
bash
echo "${name:0:4}"

Offsets are zero-based.

Replace first match

Replace first matching substring.

bashANYreplacestrings
bash
echo "${file/.txt/.bak}"

Useful for filename transforms.

Replace all matches

Replace all matching substrings.

bashANYreplacestrings
bash
echo "${path//\//:}"

The doubled slash means global replacement.

Remove shortest prefix

Strip shortest matching prefix pattern.

bashANYprefixsuffixpatterns
bash
echo "${path#*/}"

Handy for path processing.

Remove longest suffix

Strip the longest matching suffix pattern.

bashANYprefixsuffixpatterns
bash
echo "${file%%.*}"

Useful for basename-like operations and extensions.

Globbing and Brace Expansion

Filename matching and brace generation.

Match files with glob

Expand a glob to matching files.

bashANYglobfiles
bash
printf '%s
' *.txt

Globs are expanded by the shell before command execution.

Brace expansion

Generate multiple words from a brace expression.

bashANYbrace-expansiongeneration
bash
printf '%s
' file-{a,b,c}.txt

Brace expansion happens before pathname expansion.

Sequence expansion

Generate a numeric sequence.

bashANYbrace-expansionsequence
bash
printf '%s
' {1..5}

Great for loops and quick test data.

Enable nullglob

Expand unmatched globs to nothing.

bashANYglobshopt
bash
shopt -s nullglob

Safer than leaving a literal pattern in loops.

Include dotfiles in globs

Make globs match dotfiles too.

bashANYglobshopt
bash
shopt -s dotglob

Useful for file moves and maintenance tasks.