Arithmetic Operations
Basic Arithmetic Calculations
Expr provides a straightforward way to perform arithmetic operations directly from the command line or within shell scripts.
Addition
result=$(expr 10 + 5)
echo $result ## Outputs: 15
Subtraction
result=$(expr 20 - 7)
echo $result ## Outputs: 13
Multiplication
result=$(expr 6 \* 4)
echo $result ## Outputs: 24
Operator Precedence and Complexity
graph TD
A[Arithmetic Operators] --> B[Basic]
A --> C[Advanced]
B --> B1[+ Addition]
B --> B2[- Subtraction]
B --> B3[* Multiplication]
B --> B4[/ Division]
C --> C1[Parentheses]
C --> C2[Precedence Rules]
C --> C3[Complex Expressions]
Handling Complex Expressions
Division
result=$(expr 15 / 3)
echo $result ## Outputs: 5
Modulus Operation
result=$(expr 17 % 5)
echo $result ## Outputs: 2
Advanced Arithmetic Techniques
Nested Calculations
result=$(expr \( 10 + 5 \) \* 2)
echo $result ## Outputs: 30
Common Pitfalls and Best Practices
Scenario |
Recommendation |
Multiplication |
Always escape * with * |
Division |
Use integer division |
Complex Expressions |
Use parentheses carefully |
Error Handling
## Handling potential errors
if expr 10 / 0 > /dev/null 2>&1; then
echo "Calculation successful"
else
echo "Error in calculation"
fi
While expr is convenient, for complex or performance-critical calculations, consider alternatives like:
- Bash arithmetic expansion
$((...))
- bc command
- Programming language specific calculations
LabEx Tip
In LabEx Linux programming environments, always test arithmetic expressions thoroughly to ensure expected behavior across different scenarios.