KandZ – Tuts

We like to help…!

Linux CLI 61 🐧 modern test version and in (( )) shell scripts

a - extended test command in shell scripts
Unlike the traditional [ ] (or test) which requires spaces around operators, [[ ]] does not have this requirement.
It's generally recommended to use [[ ]] over [ ] for most modern shell scripting needs due to its enhanced functionality and error prevention.
Unlike [ ], [[ ]] does not split words or do pathname expansion unless explicitly told to with *.
Using [[ ]] can lead to more robust and error-free scripts compared to the older [ ], especially in complex conditions involving strings, patterns, or file tests.
String Comparison Without Quotes:
[ $var1 = test ]: Without quotes, if var1 is empty or contains spaces, it will cause a syntax error. Using quotes ([ "$var1" = "test" ]) avoids this issue.
[[ $var1 = test ]]: With [[ ]], you don't need to quote variables unless they contain special characters or are empty. This makes the code cleaner and less error-prone.
Pattern Matching:
[ $var2 = test* ]: Using pattern matching without quotes can lead to unexpected results due to word splitting and pathname expansion.
[[ $var2 =~ test.* ]]: With [[ ]], you can use the =~ operator for regex matching, which is more flexible and powerful.
Numeric Comparisons:
Both [ ] and [[ ]] support numeric comparisons similarly (-eq, -ne, etc.), but [[ ]] allows for easier chaining of conditions due to its lack of word splitting issues.

b - (( )) in shell scripts
(()) is used for arithmetic evaluation. It allows you to perform mathematical operations and handle integer arithmetic directly within your scripts
syntax:
result=$((expression))
expression: This can include any valid arithmetic operation involving integers, such as addition (+), subtraction (-), multiplication (*), division (/), modulus (%), and exponentiation (using ** in some shells).
Key Points
1. Integer Arithmetic Only: (()) supports only integer arithmetic. If you need floating-point calculations, you would typically use tools like bc or awk.
2. Expression Evaluation: The entire expression within (()) is evaluated to a single integer value.
3. Precedence and Associativity: (()) follows the standard mathematical precedence rules (multiplication and division before addition and subtraction). Parentheses can be used to alter the order of operations.
example 1 → Simple Arithmetic Operations
example 2 → Using Variables and Expressions
example 3 → Incrementing and Decrementing Variables
example 4 → Using Exponentiation

Leave a Reply