More math on the Linux command line

Using double-parens

Another easy way to do integer math is to use double parentheses as in the examples below. As with the expr command, multiplications and divisions are done prior to additions and subtractions.

$ echo $((3 + 4))
7
$ echo $((10 * 5))
50
$ echo $((24 / 3))
8
$ echo $((10 * 5 + 1))
51
$ echo $((1 + 5 * 10))
51
$ echo $((1 + 10 / 5))
3

Keep in mind that the double-parens method only supports integers.

$ echo $((10 / 2.5))
-bash: 10 / 2.5: syntax error

Using the bc command

The bc command is used for more precision calculations. While it is a language in itself, it is frequently used for floating point mathematical operations as in the examples below.

$ echo "12+5" | bc
17
$ echo "10^2" | bc
100
$ echo "3 + 4" | bc
7
$ echo "scale=2; 10 / 3" | bc
3.33
$ echo 11.11 + 4.3 | bc
15.41

The scale argument allows you to set the decimal precision that you want.

The bc command also supports more advanced math with the -l (math library) option that handles numbers as floating point objects:

$ echo 100/3 | bc
33
$ echo 100/3 | bc -l
33.33333333333333333333

Using awk

The awk command is easy to use and works for both integer and floating-point math. Here are a few examples:



Source link

Leave a Comment