$cat add_variables_02.shExecute in a shell
#! /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
$bash add_variables_02.shThe 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.
13
13
10+3
10+3
13
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
- info coreutils 'expr invocation'
- man expr
Special thanks to the anon 2011-08-24 5:06 AM for providing the first two methods.
3 comments:
Why not just nv=$((ov+3)) or ((nv=ov+3))? Running external command in a subprocess is slower than using Bash's own feature.
Thanks for the feedback. I updated the post with your suggestions.
Thanks for sharing. I looked for something this simple for a while.
Post a Comment