Muffinresearch Labs by Stuart Colville

BASH Tip: Alternative to expr for arithmetic | 2 Comments

Posted in Snippets on 30th August 2007, 11:59 am by

I discovered recently a neat way to do arithmetic in BASH without the need to use the expr command. There’s a build-in that uses the syntax $((…)) or $[ … ]. This is also faster as it avoids the need to invoke a separate command. See: http://snap.nlc.dcccd.edu for more on the rules pertaining to this syntax.

Post Tools

  • Kenan Bektas

    This hint is totally cool.

    Thanks,.

    -Deniz Gezmis

  • akn

    Hi,

    Thanks for that tip. This was very useful i.e. to have a simplified replacement for the messy expr. In fact I didn’t know how to do compound statements using expr. For example how to do this expression (var1 – var2)*100/var1, since bash complains about those paranthesis. But using the other alternative I could easily compute the value as $[(var1-var2)*100/var2]. You don’t have to worry about escaping the *, + etc. in the expression. It is so easy to use! Thanks for the tip.

GNU screen: open tab in current working directory|(1)

A nice trick for having screen open a new tab in the same directory as the one you’re currently in. To use it add it to your .screenrc

# Open new window in current dir.
bind c stuff "screen -X chdir \$PWD;screen^M"
bind ^c stuff "screen -X chdir \$PWD;screen^M"

Hat tip: mteckert on SuperUser.com

Ubuntu: add-apt-repository: command not found|(3)

When you’re using a minimal Ubuntu install if you find the ‘add-apt-repository’ command is missing (it’s useful for adding PPAs and other repositories), then simply run:

sudo apt-get install python-software-properties

Photos on Flickr

© Copyright 2004-12 Stuart Colville, all rights reserved. May contain traces of Muffin. Powered by WordPress. Hosting by Slicehost.com This page was baked in 0.480s.