Basic Math Functions in Bash

Aug 21, 2024

Bash Math Functions

Introduction

  • Overview of the video and its focus on basic math functions in Bash.
  • This video is one of the shorter and easier ones in the series.

Handling Math in Bash

  • Math functions in Bash differ from languages like Python.
    • Example in Python: 30 + 10 works directly.
    • In Bash, a different approach is required.

Evaluating Expressions with expr

  • expr command is used to evaluate expressions in Bash.
  • Example of addition:
    expr 30 + 10  
    
    • Output: 40

Basic Math Operations

  • Addition:

    • Command: expr 30 + 10
    • Result: 40
  • Subtraction:

    • Command: expr 30 - 10
    • Result: 20
  • Division:

    • Command: expr 30 / 10
    • Result: 3
  • Multiplication:

    • Command: expr 100 * 4
      • Important: Use backslash to escape the asterisk:
      expr 100 \* 4  
      
    • Result: 400
    • Explanation: Asterisk (*) is a wildcard in Bash.

Using Variables in Math

  • Example of variable declaration and use in math:

    • Declare a variable:
      my_num1=100  
      
  • Adding a number to a variable:

    expr $my_num1 + 50  
    
    • Result: 150
  • Adding two variables together:

    • Declare another variable:
      my_num2=50  
      
    • Add them:
      expr $my_num1 + $my_num2  
      
    • Result: 150

Conclusion

  • Recap of what was covered regarding basic math functions in Bash.
  • Encouragement to check the next episode in the series.