Search This Blog

Wednesday, February 02, 2011

Add a number to a variable in shell script

Consider the following shell script
$cat add_variables_02.sh
#! /bin/sh
ov=10;
nv=$((ov+3)); echo $nv
((nv=ov+3)); echo $nv
nv=$ov+3; echo $nv
nv=`expr $ov+3`; echo $nv
nv=`expr $ov + 3`; echo $nv
Execute in a shell
$bash add_variables_02.sh 
13
13
10+3
10+3
13
The first two methods nv=$((ov+3)) or ((nv=ov+3)) are faster than the fifth method nv=`expr $ov + 3` as the former uses bash's own feature and the later runs an external command in a subprocess.

Also, note that spaces are needed before and after the '+' character when expr is used.

Tested in Debian Wheezy machine using bash 4.2-1

Further reading
  1. info coreutils 'expr invocation'
  2. man expr

Special thanks to the anon 2011-08-24 5:06 AM for providing the first two methods.

3 comments:

Anonymous said...

Why not just nv=$((ov+3)) or ((nv=ov+3))? Running external command in a subprocess is slower than using Bash's own feature.

Kamaraju Kusumanchi said...

Thanks for the feedback. I updated the post with your suggestions.

tommycarstensen said...

Thanks for sharing. I looked for something this simple for a while.

Followers