Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Let's say I have a command called foo which prints a number to the screen when called:

$ foo

Let's also say I have another command called bar which prints another number to the screen when called:

$ bar

I'm looking to write a shell script which will arithmetically add together the output of foo and bar (3+5=8). How would I do that? (The outputs from the commands are not known ahead of time. They just so happen to have been 3 and 5 the last time they were run. They could have been something else.)

share|improve this question
What do you mean by adding together? Are the program outputs always integers and you want 3+5=8 or are they strings and you want '3'+'5'='35'. – Benjamin Bannier Apr 22 '10 at 17:33
they're integers, and I'm looking to add them (3+5=8), not concatenate them – John Kube Apr 22 '10 at 17:36
up vote 8 down vote accepted

Use bash's let to evalutate arithmetric expressions.

a=`echo 3`
b=`echo 5`

let c=$a+$b
echo $c

Just substitute the calls to echo with your program calls.

share|improve this answer
You can omit the dollar signs in a let statement. – Dennis Williamson Apr 22 '10 at 22:34
@Dennis: I know, but this way it does at least seem consistent. The shortest way (sadly?) is often the most likely to confuse (cf. Perl ;) – Benjamin Bannier Apr 22 '10 at 22:48
let is the devil. It feels like BASIC, and makes baby pandas cry. The double-paren mechanism doesn't harm pandas. ;) – dannysauer Nov 12 '10 at 0:58

An alternative to let is to use double-parenthesis syntax:

(( c = $(foo) + $(bar) ))


echo $(( $(foo) + $(bar) ))

or using variables, you can omit the dollar sign on the right hand side of the equals:

(( c += $(foo) + num ))

(which also illustrates an incremental assignment)

If you're using non-integers you can use bc:

echo "$(foo) + $(bar)" | bc


c=$(echo "$(foo) + $(bar)" | bc)

One advantage of using double parentheses is that you can put spaces around the operands and operators to make things more readable:

(( c = ( a + b ) * ( i - j ) ))
share|improve this answer


bc < <({ foo ; echo + ; bar ; } | tr '\n' ' ' ; echo)

If the output is integers only:

$(( $(foo) + $(bar) ))
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.