Bash Scripting – Using Double Parantheses
Two additions to the bash shell provide advanced features that you can use in if-then statements:
- Double parentheses for mathematical expressions
- Double square brackets for advanced string handling functions
The double parentheses command allows you to incorporate advanced mathematical formulas in your comparisons. The test command allows for only simple arithmetic operations in the comparison. The double parentheses command provides more mathematical symbols, which programmers who have used other programming languages may be familiar with using. Here’s the format of the double parentheses command:
(( expression ))
The expression term can be any mathematical assignment or comparison expression. Besides the standard mathematical operators that thetest command uses, below table shows the list of additional operators available for use in the double parentheses command.
The Double Parentheses Command Symbols
$ cat test23.sh #!/bin/bash # using double parenthesis # val1=10 # if (( $val1 ** 2 > 90 )) then (( val2 = $val1 ** 2 )) echo “The square of $val1 is $val2” fi $ $ ./test23.sh The square of 10 is 100 $
Using double brackets
[[ expression ]]
$ cat test24.sh #!/bin/bash # using pattern matching # if [[ $USER == r* ]] then echo “Hello $USER” else echo “Sorry, I do not know you” fi $ $ ./test24.sh Hello rich $
Notice in the preceding script that double equal signs (==) are used. These double equal signs designate the string to the right (r*) as a pattern, and pattern matching rules are applied. The double bracket command matches the $USER environment variable to see whether it starts with the letter r. If so, the comparison succeeds, and the shell executes the then section commands.