Another way to use math expressions in shell scripts

Hi! If you're new here, you may want to subscribe to the Unix Tutorial RSS feed to get regular tips & tricks for all flavors of Unix. You can follow me on Twitter, too! Thanks for visiting!

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: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • BlinkList
  • Fark
  • Furl
  • kick.ie
  • Netscape
  • Reddit
  • StumbleUpon
  • Technorati
  • YahooMyWeb

2 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.

Leave a Comment