A variable in bash is a named string. The shell substitutes its value wherever it sees $name, and then (if there are no quotes) splits the result into words and expands patterns like *. That's why quoting matters more than it seems.
Syntax
name=value # no spaces around =
echo "$name" # substitute the value
echo "${name}_suffix" # braces separate the name from the text
export name # make the variable visible to child processes
unset name # delete the variable
A name is Latin letters, digits and _, and can't start with a digit. Case matters: Name and NAME are different variables.
Quoting
| Syntax | What happens |
|---|
"…" | $var, $(…), $((…)) expansions work, but the result is not split into words or expanded as a pattern |
'…' | everything is literal, no expansions; you can't put a single quote inside |
$'…' | literal, but understands escape sequences: $'a\tb', $'\n' |
\char | escape one character: \$, \", \\, \ |
| no quotes | the value is split on $IFS (space, tab, newline) and expanded as a glob |
Declaring: declare and friends
| Command | What it does |
|---|
export var=x / declare -x var | the variable goes into child processes' environment; export -n var — remove it from there |
local var=x | the variable is visible only inside the function |
readonly var=x / declare -r | a constant: can't be reassigned (in a script that's an error and an exit) |
declare -i n | an integer: n=5+3 stores 8 |
declare -l / declare -u | convert to lowercase / uppercase on assignment |
declare -a arr / declare -A map | an indexed / associative array |
declare -p var | show how the variable is declared, with type and value |
VAR=x command | a variable just for this one command |
Parameter expansion
| Form | What it gives |
|---|
${var:-x} | the value of var, or x if it's empty or unset |
${var-x} | x only if var is not set at all (an empty string counts as a value) |
${var:=x} | like :-, but also assigns x to the variable |
${var:+x} | x if var is non-empty, otherwise an empty string |
${var:?text} | an error with the text and exit from the script if var is empty |
${#var} | string length in characters |
${var#pattern} / ${var##pattern} | remove the shortest / longest match from the start |
${var%pattern} / ${var%%pattern} | remove the shortest / longest match from the end |
${var/a/b} / ${var//a/b} | replace the first / all occurrences of a with b; ${var//a/} — delete |
${var/#a/b} / ${var/%a/b} | replace a only if the string starts / ends with it |
${var:pos} / ${var:pos:len} | substring from position pos (zero-based); ${var: -3} — the last 3 characters (the space before - is required) |
${var^} / ${var^^} | first letter / whole string to uppercase |
${var,} / ${var,,} | first letter / whole string to lowercase |
${!var} | indirect reference: the value of the variable whose name is stored in var |
${var@Q} | the value quoted so it can be fed back to the shell |
Patterns in #, %, / are globs (*, ?, […]), not regular expressions.
Command substitution and arithmetic
| Form | What it gives |
|---|
$(command) | the command's stdout; trailing newlines are stripped. The old form is `command` |
$((expression)) | the result of an integer expression |
((expression)) | evaluate without substituting; exit code 0 if the result is non-zero |
let "z=2*3" | same as ((z=2*3)) |
Operators in $((…)): + - * / % **, ++ --, += -= *= /=, comparisons < <= > >= == !=, logic && || !, bitwise & | ^ ~ << >>, ternary a ? b : c. Inside $((…)) you can omit the $ before names. Numbers: 0x1F — hex, 010 — octal, 2#101 — binary, 10#08 — explicitly decimal.
Arrays
| Syntax | What it gives |
|---|
arr=(a b "c d") | create an array of three elements |
arr[5]=x | assign by index (gaps are allowed) |
arr+=(e f) | append elements to the end |
${arr[0]} / ${arr[-1]} | first / last element |
"${arr[@]}" | all elements, each as a separate word |
"${arr[*]}" | all elements as one string joined by the first character of $IFS |
${#arr[@]} | number of elements |
${!arr[@]} | list of indexes (or the keys of an associative array) |
"${arr[@]:1:2}" | slice: 2 elements starting at index 1 |
unset 'arr[1]' | delete an element (indexes don't shift) |
declare -A m; m[key]=v | associative array: keys are strings |
mapfile -t arr < file | read a file into an array, one line per element |
IFS=, read -ra arr <<< "a,b,c" | split a string on a separator into an array |
Special variables
| Variable | Value |
|---|
$0 | script name |
$1 … $9, ${10} | positional arguments; shift moves them left |
$# | number of arguments |
"$@" | all arguments, each as a separate word — almost always the one you want |
"$*" | all arguments as one string |
$? | exit code of the last command |
$$ | PID of the current shell |
$! | PID of the last background process |
$_ | last argument of the previous command |
$PIPESTATUS | array of exit codes of the parts of the last pipeline |
$BASH_REMATCH | groups of the last [[ … =~ … ]] match |
$IFS | word separators (space, tab, newline by default) |
$PWD, $OLDPWD, $HOME, $UID | current and previous directory, home directory, numeric UID |
$RANDOM, $SECONDS, $LINENO | random number 0–32767, seconds since the shell started, line number |
Examples
name=world
echo "hello $name" # hello world
echo 'hello $name' # hello $name — no expansions in single quotes
# default value
echo "${PORT:-8080}"
# a required script parameter: without it — an error and exit
: "${1:?specify a file name}"
# take a path apart without basename/dirname
p=/var/log/nginx/access.log.gz
echo "${p##*/}" # access.log.gz — file name
echo "${p%/*}" # /var/log/nginx — directory
echo "${p%.gz}" # /var/log/nginx/access.log — without the extension
echo "${p##*.}" # gz — extension only
echo "${p%%.*}" # /var/log/nginx/access — up to the first dot
# replacement and case
s="a-b-c"
echo "${s//-/_}" # a_b_c
echo "${s^^}" # A-B-C
# command output into a variable
today=$(date +%F)
# arithmetic
echo $((7 / 2)) $((7 % 2)) $((2 ** 10)) # 3 1 1024
i=5; ((i++)); ((i += 10)); echo "$i" # 16
# arrays
arr=(one two "three four")
echo "${#arr[@]}" # 3
arr+=(five)
for x in "${arr[@]}"; do echo "<$x>"; done
# associative array
declare -A port=([http]=80 [https]=443)
for k in "${!port[@]}"; do echo "$k=${port[$k]}"; done
# format a number into a variable without a subshell
printf -v id '%05d' 42 # id=00042
# a variable for one command only
LC_ALL=C sort file.txt
Pitfalls
- Spaces around
= break assignment. a = 1 runs the command a with arguments = and 1 (command not found).
- An unquoted variable is split into words. If
f="my file.txt", then ls $f looks for two files, my and file.txt. Write "$f" almost always.
"${arr[@]}" and ${arr[@]} are different. Without quotes the element "three four" falls apart into two. The same goes for "$@" vs $*.
- Arithmetic is integer-only.
$((0.5 + 1)) is a syntax error, $((7/2)) is 3. Do fractions in awk.
- A leading zero means octal.
$((010)) equals 8, and $((08)) is an error "value too great for base". For numbers like 08 from a date, write $((10#08)).
- Without
export, a child process doesn't see the variable. x=1; bash -c 'echo $x' prints an empty line.
$(…) strips trailing newlines, but not leading spaces. And local x=$(command) loses the command's exit code: $? will be the code of local.
${var: -1} and ${var:-1} are different. Without the space it's "default value 1", not "last character".
- Variable changes inside a pipeline are lost: each part of
| runs in a subshell.
See also
conditions-loops · redirection · exit-codes · shellcheck