Another way to use math expressions in shell scripts

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=1
ubuntu$ FINISH=10
ubuntu$ ELAPSED=$(($FINISH - $START))
ubuntu$ echo $ELAPSED
9

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 $ELAPSED
9

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.

See also:

Please share:
  • Digg
  • del.icio.us
  • Netvouz
  • BlinkList
  • Fark
  • Furl
  • kick.ie
  • Netscape
  • Reddit
  • StumbleUpon
  • Technorati
  • YahooMyWeb

3 comments ↓

#1 Removing Files and Directories with Special Characters | UNIX Tutorial: Learn UNIX on 09.25.08 at 9:35 pm

[...] Using math expressions in Unix shell [...]

#2 kgas on 10.20.08 at 8:01 am

Thanks for the nice web site you are maintaining. Without using the variable names we can carry out normal calculation in CLI

# echo $((80*2))

will do the normal multiplication and other simple arithmetic. Hope this will be simple for the beginner.

#3 Fixed calculations in Unix scripts — UNIX Tutorial: Learn UNIX on 06.18.09 at 4:46 pm

[...] Another way of doing calculations in scripts Please share: [...]

Leave a Comment