1. Introduction to Double Parentheses in Bash
Double parentheses ((…)) in Bash are used for arithmetic operations and evaluation of expressions. They allow you to perform calculations and comparisons in a concise and readable manner. In this context, Bash treats the content within the double parentheses as an arithmetic expression.
2. Arithmetic Operations with Double Parentheses
Performing arithmetic operations with double parentheses is straightforward. You can use them to perform basic operations like addition, subtraction, multiplication, division, and Modulus. Here are some examples:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
# Addition
((sum = 5 + 3))
echo $sum # Output: 8
# Subtraction
((difference = 10 - 4))
echo $difference # Output: 6
# Multiplication
((product = 3 * 4))
echo $product # Output: 12
# Division
((quotient = 16 / 4))
echo $quotient # Output: 4
# Modulus
((remainder = 10 % 3))
echo $remainder # Output: 1
|
3. Comparison and Logical Operators
Double parentheses can also be used with comparison and logical operators. This allows you to perform complex operations and create more expressive scripts. Here’s a list of operators you can use within double parentheses:
- Equality: `==`
- Inequality: `!=`
- Greater than: `>`
- Less than: `<`
- Greater than or equal to: `>=`
- Less than or equal to: `<=`
- Logical AND: `&&`
- Logical OR: `||`
Here’s an example using comparison and logical operators:
1
2
3
4
5
6
7
8
9
10
|
((a = 5))
((b = 10))
((c = 15))
if (( a < b && b < c )); then
echo "b is between a and c."
else
echo "b is not between a and c."
fi
# Output: b is between a and c.
|
4. Nested Expressions
Double parentheses also allow for nested expressions, providing even more flexibility. You can use nested double parentheses to create more complex arithmetic expressions:
1
2
|
((result = 5 * (3 + 2) - (10 / 2)))
echo $result # Output: 20
|
5. Using Double Parentheses for Flow Control
You can use double parentheses with loops and conditional statements to control the flow of your script. Here’s an example using a for loop:
1
2
3
4
|
# Countdown from 10 to 1
for ((i = 10; i >= 1; i--)); do
echo $i
done
|
Here’s another example using a while loop:
1
2
3
4
5
6
7
8
9
10
|
# Sum of the first 10 positive integers
((sum = 0))
((i = 1))
while ((i <= 10)); do
((sum += i))
((i++))
done
echo $sum # Output: 55
|
Conclusion
Double parentheses ((…)) in Bash provide a powerful and concise way to perform arithmetic operations, evaluate expressions, and control the flow of your script. By mastering the use of double parentheses, you can write more expressive and efficient Bash scripts.
Copied from: https://tecadmin.net/double-parentheses-in-bash/