This the basic Bash Script quick reference useful to those, who do not often write bash scripts, and need an intermitent refresher on how basic things are done. This is not a comprehensive reference, nor will it be of use to any one who is more experienced with Bash shell.
Bash expressions contain variables and operators such as == (equals) and > (greater
than). These operators are usually used in tests, which can be specified in several ways:
test $file == "test"
[ $file == "test" ]
[[ $file == "test" ]]
If you use the test command, remember that some symbols have multiple meanings
(for instance, in an earlier section we used > for output redirection), so they need to
be enclosed in quotes. You don’t have to worry about the quotes if you use the single
or double square bracket syntax. The double brackets do everything the single
ones do and a bit more, so it’s safest to use double brackets with your expressions.
bash has some useful special built-in operators:
-a file # true if file exists
-d file # true if file exists and is a directory
-f file # true if file exists and is a file
-r file # true if file exists and is readable
-w file # true if file exists and is writable
-x file # true if file exists and is executable
bash is heavily weighted toward text such as commands, arguments, and filenames.
It can evaluate the usual arithmetic expressions (using +, -, *, /, and other operators)
by surrounding them with a pair of double parentheses: ((expression)). Because
many arithmetic characters–including *, (, and )–are specially interpreted by the
shell, it’s best to quote shell arguments if they will be treated as math expressions in
Simple calculator (./calc)
result=$(( $* ))
$ ./calc "(10+1)*(9-1)-40"
$ ./calc "2*100"
The latest version of bash supports 64-bit integers, while older versions only supported 32-bit. Floating-point numbers are not supported. Scripts that need floating-point or more advanced operators can use an external program
such as bc.
The if … fi
Given expressions, you can execute different chunks of code depending on the
results of tests. bash uses the if … fi (backwards if) syntax, with optional elif
(else if) and else sections:
if expression1 ; then
elif expression2 ; then
elif expressionN ; then
The ; then phrase at the end of a line can also be expressed as a plain then on the
Taken from goitexpert.com