Linux Shell Arithmetic Operations

In the Linux Shell, basic integer arithmetic operations can be performed using the built-in command expr, while the bc command can be used for floating point calculations.

Below is an example code for integer operations.

#!/bin/bash

# 整数四则运算
num1=10
num2=5

# 加法
result=$(expr $num1 + $num2)
echo "加法结果:$result"

# 减法
result=$(expr $num1 - $num2)
echo "减法结果:$result"

# 乘法
result=$(expr $num1 \* $num2)
echo "乘法结果:$result"

# 除法
result=$(expr $num1 / $num2)
echo "除法结果:$result"

An example code for arithmetic operations with floating point numbers is shown below:

#!/bin/bash

# 浮点数四则运算
num1=10.5
num2=2.5

# 加法
result=$(echo "$num1 + $num2" | bc)
echo "加法结果:$result"

# 减法
result=$(echo "$num1 - $num2" | bc)
echo "减法结果:$result"

# 乘法
result=$(echo "$num1 * $num2" | bc)
echo "乘法结果:$result"

# 除法
result=$(echo "scale=2; $num1 / $num2" | bc)
echo "除法结果:$result"

In the provided code, the expr command is used for integer operations while the bc command is used for floating-point calculations. The scale option in the bc command is used to set the precision of floating-point calculations.

bannerAds