Wednesday, December 5, 2012

Arithmetic In The Unix Shell

We often need to do arithmetic in the shell. There are better tools than the shell for computation, but there are practical situations when we need to do this in the shell. E.g. you need to sum the time taken between a set of logged events.

I can think of three ways to do this.

The first is the POSIX feature $((expression))
The shell evaluates expression and substitutes its result.
# echo $(( 2*(1+1) ))
4

The second is using expr. Here the spaces are required and we need to quote * because it is a shell metacharacter.
# expr 2 \* \( 1 + 1 \)
4

The third is using the unix utility bc. This is by far the most portable method.
# echo '2*(1+1)' | bc
4

No comments:

Post a Comment