Bash Math Functions
Introduction to Math Functions in Bash
- Bash offers a variety of built-in commands and functions.
- This video focuses on math functions in Bash.
Handling Math in Bash
- Math functions are not frequently used but contribute to a well-rounded knowledge of Bash.
- Different shells and programming languages handle math differently.
- Example: In Python, adding 30 and 10 can be done directly as
30 + 10.
Evaluating Expressions with expr
- Bash requires a specific syntax to understand math operations.
- The
expr command is used to evaluate expressions. - Example:
expr 30 + 10 will output 40.
Basic Arithmetic Operations
- Addition: Use
expr followed by the numbers with a plus symbol. - Subtraction: Use
expr followed by the numbers with a minus symbol.- Example:
expr 30 - 10 outputs 20.
- Division: Use
expr followed by the numbers with a forward slash.- Example:
expr 30 / 10 outputs 3.
Multiplication and Escaping Special Characters
- Multiplication: Use
expr with an escaped asterisk. - The asterisk
* is a wildcard in Bash, meaning "everything". - To use it for multiplication, escape it with a backslash
\. - Escaping special characters is necessary when they have other purposes in Bash.
Using Variables in Math Functions
- Variables can be used in math functions.
- Example:
my_num1=100expr $my_num1 + 50 will output 150.
- Another Example:
my_num2=200expr $my_num1 + $my_num2 will output 300.
Practical Application and Conclusion
- This knowledge may not seem immediately useful but can be helpful in future scenarios.
- It provides a foundation for performing math functions in Bash, especially for those familiar with other shells or programming languages.