Today I'd like to expand a bit more on the basic calculations in Unix scripts.

### Use Parenthesis to simplify math expressions

In Basic Arithmetic Operations post I've shown you how expression evaluation can be used to calculate simple math expressions in your Unix shell:

ubuntu$START=1ubuntu$FINISH=10ubuntu$ELAPSED=$(($FINISH - $START))ubuntu$echo $ELAPSED9

Although this approach looks clean enough, there's a way to simplify it even further if you put everything in parenthesis. In other words, the same result (ELAPSED receiving a correct value of FINISH value minus START value) can be achieved this way:

ubuntu$((ELAPSED=FINISH-START))ubuntu$echo $ELAPSED9

It's a matter of preference, and I used to always do such calculations the former way shown, but now that one of the readers of this blog pointed out the latter way of using it, I think I might change my habits – I actually like this way much better.

Pingback: Removing Files and Directories with Special Characters | UNIX Tutorial: Learn UNIX

Pingback: Fixed calculations in Unix scripts — UNIX Tutorial: Learn UNIX