Mastering Arithmetic Expressions with the Shell.

COURSE LESSON

Continue your learning

Sign in to access your enrolled courses, or view the course details before enrolling.

Sign in View course

The shell is a powerful tool that extends its functionality through scripting and command-line expressions. One of its lesser-known but highly useful features is its ability to perform arithmetic calculations directly from the command line. This capability is particularly handy for users who need quick computations without diving into a full calculator or script.

Question

Can I perform basic arithmetic operations in the shell?

Bash, like many Unix shells, supports basic arithmetic operations using parentheses and the - operator. For example:

  • Addition: echo $((5 + 3)) will output 8.
  • Subtraction: echo $((10 - 2)) yields 8.

Question

How can I perform multiplication and division in the shell?

Multiplication and division are supported using parentheses with the respective operators. For instance:

  • Multiplication: echo $((5 * 3)) outputs 15.
  • Division: echo $((10 / 2)) gives 5.

Question

What about exponentiation in the shell?

Bash does not support exponentiation directly with a special operator. However, you can use the square of a number by raising it to the power of 2, such as:

  • echo $((4^2)) outputs 16.

Question</hًا