This question already has an answer here:

How can I assign value of $x1+$x2 to bc by piping? here in my code $bc holds no value.

echo -n 'value x1 : '
read x1
echo -n 'value x2 : '
read x2
echo $x1+$x2 | bc
echo $bc

marked as duplicate by Drav Sloan, jimmij, eyoung100, don_crissti, Gilles bash Aug 10 '15 at 22:47

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Checkout the bash man page section on "Command Subsitution". – larsks Aug 10 '15 at 18:25
  • Say i choose 5 and 12 as the numbers: Are you trying to get the total in the variable bc (17) or are you trying to get the string (5+12 )? – user1794469 Aug 10 '15 at 18:36
  • 1
    x1=4; x2=3; x=$((x1+x2)); echo $x – Cyrus Aug 10 '15 at 19:02
  • What does piping have to do with it? It sounds like you just want to assign the result of $x1+$x2 to a variable, and you somehow decided piping is the right way to do that – Michael Mrozek Aug 10 '15 at 19:44
  • General note: Piping means forwarding the output of a previous command as the input of the next command, e.g. echo 1,2,3 separated by tabs and then cut to display the first column only: cat -e 1\\t2\\t3 | cut -f1 . For assigning the output of a command to a variable, use variable=$( command ) – Fiximan Aug 10 '15 at 20:08

is easy and there are many ways to do, for example

v=$(echo $x1+$x2 | bc)  
v=`echo $x1+$x2 | bc`

Note that bc is integer arithmetics only and that you need bc -l for a proper math library. Note that you can skip the echoing with the 'here' redirection <<< for strings:

v=$( bc <<< $x1+$x2 )
  • 2
    Backquotes are exactly equivalent to capturing parens, but they don't nest and they're harder to read. Avoid them except for interactive use if you find it easier to type them. – Peter Cordes Aug 10 '15 at 20:08

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