BASH Scripting: Parenthesis Explained

Author: Tobin Harding
Here we briefly outline some of the major use cases for brackets, parenthesis,
and braces in BASH scripting, see bottom of page for definition of
these three terms.

Double parentheses (( )) are used for arithmetic:

((var = 3))
for ((i = 0; i < VAL; i++))
echo $((var + 2))

Variables used inside double parentheses do not need to be prefixed
with '$'.

Square brackets [] are used for test construct

$ VAR=2
$ if [ $VAR -eq 2 ]
> then
> echo 'yes'
> fi

Double square brackets [[]]offer extended functionality to single
square brackets, useful for the regular expression operator =~

$ VAR='some string'
$ if [[ $VAR =~ [a-z] ]]; then
> echo 'is alphabetic'
> fi
is alphabetic

Curly braces {} are used to delimit a variable

$ foo='stage'
$ echo $fooone
           ... returns empty line
$ echo ${foo}one

Curly braces are also used for parameter expansion

$ var="abcdefg"; echo ${var%d*}

There are many more uses for parentheses, brackets, and braces in
BASH. Just remember, single square for 'test', double square for reg
ex, and double parentheses for arithmetic and C style loops. Good luck


Parenthesis: ()
(plural parentheses)
Brackets: []
(also called square brackets)
Braces: {}
(also called curly braces)

Comments and Discussions
Linux Forum