In Bash, square brackets “[]”, single parentheses “()” and double parentheses “(( ))” are used in different contexts within “if” statements.
Here’s the breakdown of their common use cases with examples on usage of square brackets “[]”, single parentheses “()” and double parentheses “(( ))” in bash.
1. Square Brackets “[]”:
– Used for basic conditional tests.
– The expressions inside square brackets are treated as strings.
– Commonly used for file tests, string comparisons, and numeric comparisons.
Example:
if [ -f "$file_path" ]; then echo "File exists." fi
In the above example, the -f test operator checks if a file exists within if statement.
2. Double Parentheses “(( ))”:
– Used for arithmetic evaluations.
– Allows the use of mathematical expressions and variables without needing the dollar sign “$”.
– Commonly used for numeric comparisons and arithmetic operations.
Example:
if (( count > 10 )); then echo "Count is greater than 10." fi
Here, the (()) is used for arithmetic comparison within an if statement.
3. Single Parentheses “()”:
– Used for command substitution.
– Executes the commands within the parentheses and substitutes the result.
– Commonly used to capture the output of a command and use it within an expression.
Example:
if [ "$(uname)" == "Linux" ]; then echo "Running on Linux." fi
In the above example, $(uname) runs the uname command and substitutes its output in a buffer within if statement and checks if it has string Linux.
In summary:
– “[]” is for basic conditional tests and string comparisons.
– “(( ))” is for arithmetic evaluations and numeric comparisons.
– “() is for command substitution, capturing command output for use in expressions.
It’s important to note that spaces are crucial in these constructs. There should be spaces between the square brackets, double parentheses, and operands. Also, within double parentheses, there is no need to prefix variables with the dollar sign “$” for arithmetic operations.
How do you feel about this post? Drop your comments below..
Click here!!! to explore more scenrios on bash scripting with various real time use case examples.