0

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
Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
Maruf
  • 1
  • 1
  • 4
  • 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 )` – FelixJN Aug 10 '15 at 20:08

1 Answers1

2

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 )
FelixJN
  • 12,616
  • 2
  • 27
  • 48
Dany Flores
  • 141
  • 3
  • 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