Mastering Division of Variables in Bash
One of the common tasks you'll encounter when scripting in Bash is performing arithmetic operations on variables, particularly division. This process might seem straightforward, but it requires careful attention due to the lack of floating-point support in Bash by default. In this article, we will dive into several methods for dividing variables in Bash, and you'll discover how to handle the lack of floating-point division in Bash.
Using the 'expr' Command
One of the commands you can use for division in Bash is
expr. This command evaluates an expression and prints the result to the console. The basic syntax is:
x=60 y=-3 result=$(expr $x / $y) echo "Result: $result"
In this case, the value of
x is divided by
y, and the result is stored in the
result variable. It's crucial to remember that the spaces before and after the division operator
/ are important. If there are no spaces, the expression supplied to the
expr command is evaluated as a string, causing a syntax error.
expr command has limitations. It only supports integer division, meaning if the result should be a floating-point number, it will be truncated to an integer. Furthermore, it cannot accept a floating-point number as input.
Utilizing Double Parentheses
Another way to perform division is using the double parentheses syntax. This syntax is a shorthand method for arithmetic operations in Bash:
x=60 y=-9 result=$(($x / $y)) echo "Result: $result"
expr command, the double parentheses syntax doesn't require spaces before and after the division operator. However, it still only supports integer division and doesn't accept floating-point numbers as input.
Commanding 'printf' for Precision
printf command is another handy tool for division in Bash. It can return a floating-point number, giving you a more precise result:
x=60 y=-9 printf "%.4f\n" $((10**4 * x/y))e-4
In this example,
x is first multiplied by 10^4, then divided by
y. The format specifier
%.4f\n formats the output as a floating-point number with four digits after the decimal point. However, note that the numerator and the denominator must still be integers.
Leveraging the 'bc' Command
bc (Basic Calculator) command is one of the most versatile tools for division in Bash. Unlike the previous methods, it allows the use of floating-point numbers as input:
x=10.5 y=-2 echo "scale=4; $x / $y" | bc
scale=4 specifies the number of digits after the decimal point in the result. Also, you can use shell variables with the
bc command by using the shell pipe
Source: Linux Journal - The Original Magazine of the Linux Community
Leave a Reply
You must be logged in to post a comment.