Arithmetic Operations in Shell Scripting

In shell scripting, you can perform numerical operations using various tools and techniques. Here are some common ways to work with numbers in a shell script:

  1. Using Arithmetic Operators:
  • Addition +
  • Subtraction -
  • Multiplication *
  • Division /
  • Modulus %
  • Exponentiation ** (in some shells)

For example, in a shell script, you can do something like:

Bash
#!/bin/bash

num1=10
num2=5

sum=$((num1 + num2))
diff=$((num1 - num2))
product=$((num1 * num2))
quotient=$((num1 / num2))
remainder=$((num1 % num2))

echo "Sum: $sum"
echo "Difference: $diff"
echo "Product: $product"
echo "Quotient: $quotient"
echo "Remainder: $remainder"

  1. Using External Tools:
  • bc: A command-line calculator that can handle floating-point arithmetic.

Example:

Bash
#!/bin/bash

num1=10
num2=5

sum=$(echo "$num1 + $num2" | bc)
echo "Sum: $sum"

result=$(echo "scale=2; $num1 / $num2" | bc)
echo "Result (with two decimal places): $result"

  1. Using expr:
  • The expr command in shell scripting is used for performing basic arithmetic operations and evaluating expressions. It works primarily with integers, so it’s not suitable for floating-point arithmetic.
  • expr is a shell command that can be used for basic arithmetic operations. However, it only works with integers.

Example:

Bash
#!/bin/bash

num1=10
num2=5

sum=$(expr $num1 + $num2)
echo "Sum: $sum"

diff=$(expr $num1 - $num2)
echo "Difference: $diff"

  1. Using Command Substitution:
    Command substitution is a feature in shell scripting that allows you to capture the output of a command and use it as a value in your script. This can be useful for tasks like assigning the result of a command to a variable or using it as an argument to another command.

Example:

Bash
 #!/bin/bash

num1=10
num2=5

sum=$(($num1 + $num2))
echo "Sum: $sum"

  1. Floating-Point Arithmetic:
    In shell scripting, performing floating-point arithmetic can be a bit more complex than integer arithmetic, as the shell’s native arithmetic operations are typically limited to integers. However, you can use external tools like bc or use a language like Python, which has built-in support for floating-point arithmetic.

Example:

Bash
#!/bin/bash

num1=10.5
num2=3.2

# Using bc for floating-point arithmetic
sum=$(echo "$num1 + $num2" | bc -l)
echo "Sum: $sum"

result=$(echo "scale=2; $num1 / $num2" | bc -l)
echo "Result (with two decimal places): $result"

Remember to be mindful of variable types (integer vs floating-point) and handle edge cases like division by zero if relevant to your specific script.

Share
OpenLib .

OpenLib .

The Founder - OpenLib.io

You may also like...