Bash Syntax Reference

This page is meant as a reference, to be searched. If you encounter an unfamiliar piece of bash syntax, you can look it up here to find out what it means. As such, it's more useful to people who are trying to read a script (which someone else wrote), rather than trying to write one.

If you're trying to write a new bash script, other resources include BashGuide, BashSheet, BashPitfalls and BashProgramming.

The sheer number of combinations of syntax characters in bash is massive, so this list may be incomplete.

Syntax

Example

Explanation

~

cd ~/bin

TildeExpansion, resulting in the current user's home directory.

~

mode=$((mode & ~umask))

In an ArithmeticExpression, bitwise NOT (negation).

~user

cd ~john

Expands to the home directory of user.

`

eval `resize`

Deprecated form of CommandSubstitution. See BashFAQ/082.

!

if ! myfunc; then myerrorhandler; fi

Reverses the exit status of a pipeline.

!

[[ ! -d $d ]]

Inside [[ or [ or test, before a unary operator, reverses the check.

!

echo [!x]*

As the first character inside a [...] in a glob, reverses the set of matched characters.

!!

!!

Repeat the previous command. (Only if HistoryExpansion is enabled.)

!word

!make

Repeat the previous command starting with word (if history expansion is enabled).

!-number

!-3

Repeat the command number entries in the past (if history expansion is enabled).

$!

pid=$!

Expands to the process ID of the most recent background pipeline.

${!var}

local arg2="${!2}"

Indirect parameter expansion; uses the value of var as a variable name and expands it.

${!arr[@]}

for i in "${!arr[@]}"

Expands to all indices of an indexed or associative array variable. The double quotes are required for associative arrays.

!(patterns)

rsync -a !(*~) "$dest"

Extended glob which matches all strings/files not matching the patterns.

"$@"

exec foo "$@"

Expands to all positional parameters, like "$1" "$2" .... The double quotes are required.

"${arr[@]}"

find "${args[@]}"

Expands to all values in an indexed array variable. The double quotes are required.

${!prefix@}

echo "${!BASH@}"

Expands to the names of variables beginning with prefix.

${var@Q}

ssh host "rm ${file@Q}"

Expands var in a quoted form which can be used in a raw bash command.

@(patterns)

[[ $input = @(foo|bar) ]]

Extended glob which matches all strings/files that match any of the patterns.

#

# look for serial number

Any word beginning with # starts a comment; the rest of the line is ignored.

$#

if (($# < 2)); then usage; fi

Expands to the number of positional parameters.

${var#prefix}

var=${var#?}

Expands to the value of var with the shortest prefix removed if present.

${var##prefix}

base=${file##*/}

Expands to the value of var with the longest prefix removed if present.

${#var}

len=${#string}

Expands to the length of var in characters (not bytes unless in the C or POSIX locale).

${#arr[@]}

size=${#arr[@]}

Expands to the number of values in an indexed or associative array variable.

$

[[ $serial =~ x[0-9]+$ ]]

In a basic/extended regular expression, matches the end of the input. Also called an anchor.

$$

kill -INT $$

Expands to the process ID of the current shell (never a subshell).

$var

cd "$foo" || exit

Expands to the value of the variable var.

${var}

echo "I like ${fruit}s"

Expands to the value of the variable var. Not a substitute for Quotes.

$(cmd)

output=$(cmd)

CommandSubstitution, expands to the standard output of cmd.

$((exp))

i=$((i+1))

ArithmeticExpression, expands to the value of exp evaluated in a math context.

${var%suffix}

dir=${file%/*}

Expands to the value of var with the shortest suffix removed if present.

${var%%suffix}

major=${version%%.*}

Expands to the value of var with the longest suffix removed if present.

^

if foo ^ grep bar >/dev/null

Synonym for | in the Bourne shell only (not bash or POSIX sh).

^

[[ $serial =~ ^[0-9]+z ]]

In a basic/extended regular expression, matches the start of the input. Also called an anchor.

^

echo [^x]*

As the first character inside a [...] in a glob, reverses the set of matched characters. Not POSIX.

^

x=$((y ^ 0xff))

In an ArithmeticExpression, bitwise XOR (exclusive OR).

${var^}

echo "${name^}"

Expands to the value of var with the first character capitalized.

${var^pattern}

echo "${name^[aeiou]}"

Expands to the value of var with the first character capitalized only if it matches pattern.

${arr[@]^}

echo "${title[@]^}"

Expands to the values of an indexed or associative array variable with the first character of each value capitalized.

${arr[@]^pattern}

echo "${title[@]^[aeiou]}"

Expands to the values of an array variable with first characters capitalized if they match pattern.

${var^^}

caps=${name^^}

Expands to the value of var with all characters capitalized.

${var^^pattern}

var=${var^^[aeiou]}

Expands to the value of var with all characters which match pattern capitalized.

${arr[@]^^}

caps=("${arr[@]^^}")

Expands to the values of an indexed or associative array variable with all characters capitalized.

${arr[@]^^pattern}

silly=("${arr[@]^^[aeiou]}")

Expands to the values of an array variable with all characters matching pattern capitalized.

^old^new^

^.txzt^.txt^

Repeat the previous command replacing old with new (only if history expansion is enabled).

&

updatedb &

Run a pipeline in the background.

&

mode=$((mode & ~umask))

In an ArithmeticExpression, bitwise AND.

&&

(i > 4) && ((i-=4))

Execute the next command only if the previous command succeeded (exit status 0).

&&

[[ -d $dir && ! -L $dir ]]

In [[, between expressions, logical AND.

*

rm *.bak

In a glob, matches any string (including the empty string).

*

[[ $serial =~ -([0-9]*)- ]]

In a basic/extended regular expression, matches 0 or more of the previous token.

"$*"

printf '%s\n' "$*"

Expands to a single string containing all positional parameters, with the first character of IFS between them. The quotes are required.

"${arr[*]}"

printf '%s\n' "${words[*]}"

Expands to a single string containing all values of an indexed or associative array variable, with the first character of IFS between them. The quotes are required.

*(patterns)

var=${var##*([[:space:]])}

In an extended glob, matches 0 or more instances of the patterns.

(cmd)

(cd "$dir" && make)

Execute cmd in a SubShell.

((exp))

((i++))

Evaluate exp as an ArithmeticExpression and exit 0 if the value is non-zero (true), or 1 if the value is 0 (false).

(To be continued.)


CategoryShell