7- BASH Scripting- Advanced uses of If-then conditional statement
Welcome Linux –fanatics, this is 7th tutorial in BASH scripting series. In our previous scripting tutorial, we discussed File, String & Numeric comparisons (also check out rest of scripting tutorials HERE). We will now be discussing some advanced uses of If-then statement in BASH scripting. So, let’s start….
Using logical operators && (AND operator) and || ( OR operator)
&& is logical AND operator. When used with if-then statement will only trigger when all the conditions are TRUE.
Syntax used is
[ condition ] && [ condition ]
|| is logical OR operator. When used with if-then statement will only trigger when any of the conditions are TRUE.
Syntax used is
[ condition ] || [ condition ]
Similarly we can also use OR operator which works if any of the given conditions is met, then statement will be triggered.
Double Parenthesis “ (( )) “
It is used for handling advanced mathematical expressions. Parameters used with “ (( )) ” are
- val ++ post increment (increases value by one)
- val– post decrement (decreases value by one)
- ++val pre increment (increases value by one)
- –val pre decrement (decreases value by one)
- ! logical negation (Not operator)
- && logical AND operator
- || logical OR operator
- ** exponential
- ~ bitwise NOT operator
- & bitwise AND operator
- | bitwise OR operator
- << left bitwise shift
- >> right bitwise shift
Important Note:- When using double parenthesis, we don’t need to escape the parameters i.e. using \ is not required.
Double Brackets “[[ ]]”
It is advanced version of “[ ]” & provides us with advanced features for string comparisons.
Here “ == ” is used for pattern matching, where == looks for “r” at start of username and if found , condition is TRUE. We can also use “!=” which would be TRUE when “r ” si not found at start of username.
So, this completes our tutorial for BASH scripting, in this tutorial we learned advanced uses of if-then conditional statement. In our next tutorial, we will learn about for conditional statement.
Also please mention you feedback/queries down below in comment box. ADIOS !!!