Bash is a powerful shell scripting language that provides a wide range of commands for various operations. One of the most important commands in Bash is the “expr” command, which is used for performing basic arithmetic operations and string manipulation. The “expr” command allows you to perform mathematical calculations, evaluate expressions, and manipulate strings in a Bash script.

Advertisement

The “expr” command is a part of the coreutils package, which is installed by default on most Unix-based systems, including Linux and macOS. It takes one or more arguments as input, and based on the type of input, it performs the appropriate operation. For example, if you pass two numbers as input, the “expr” command will perform a basic arithmetic operation like addition, subtraction, multiplication, or division, and return the result.

In this article, we will discuss a few practical examples of using the “expr” command in Bash scripts. These examples cover a wide range of use cases and will help you understand how to use the “expr” command effectively in your own scripts.

  1. Calculating the sum of two variables

    The following command calculates the sum of two variables and assigns the result to a third variable:

  2. Subtracting two variables

    The following command subtracts the value of the second variable from the first variable and assigns the result to a third variable:

  3. Multiplying two variables

    The following command multiplies two variables and assigns the result to a third variable:

  4. Dividing two variables

    The following command divides the value of the first variable by the second variable and assigns the result to a third variable:

  5. Finding the remainder of two variables

    The following command finds the remainder of the division of two variables and assigns the result to a third variable:

  6. Incrementing a variable

    The following command increments the value of a variable by 1:

  7. Decrementing a variable

    The following command decrements the value of a variable by 1:

  8. Calculating the average of a list of numbers

    The following command calculates the average of a list of numbers:

    Output: 30

Conclusion

The “expr” command is a powerful tool for performing arithmetic and string operations in Bash scripts. With the examples presented in this article, you can see the wide range of use cases for the “expr” command. These examples cover some of the most common use cases, but there are many more ways to use the “expr” command in your Bash scripts. Whether you are a beginner or an experienced Bash user, understanding the “expr” command is essential for writing powerful and efficient Bash scripts.

Share.
Leave A Reply


Exit mobile version