-1

I am new to shell scripting and i am trying to assign the output of this line to a variable but all efforts are in vain.

var2=$(cat "filename")
var1=$(echo " $var2 +3 " | bc )

var2 is properly read from the file and also the output shows the value of the sumation, but the value is not assigned to the var1

ps : Filename contains a single entry which is a number

vigneshhegde
  • 67
  • 1
  • 8
  • Have you checked the result without assigning?? – Karoly Horvath Dec 18 '15 at 12:16
  • please edit you Q to include what is in the file `filename` and expected output. More importantly, your shell has modern cmd-substitution (i.e. `$(....)`), then it also has arithmetic substitution, i.e. `var2=$(( $a + $b / $c))` and just plain arithmetic evaluations with `if (( $a > 5)) ; then ...` so generally, you don't need `bc`. (yes there are cases where you might). (and in those arithmetic tests, you don't even need the leading `$` chars (unless like $1)). I have not downvoted. Good luck! – shellter Dec 18 '15 at 12:23
  • When you run that snippet of code directly (and just that code) you see the output from `bc` displayed to the terminal directly and `var1` is empty? Because that doesn't sound right. – Etan Reisner Dec 18 '15 at 12:28
  • 1
    `var1=$(echo " $var2 +3 " | bc ) ; echo $var1 ` has an output which looks so `4.223 ` there is only a empty space when i try to output the value @EtanReisner – vigneshhegde Dec 18 '15 at 12:38
  • What about if you add `set -x` to the top and add `declare -p var2 var1` at the end? What does the complete output from that look like? – Etan Reisner Dec 18 '15 at 12:49

2 Answers2

1

The code worked when i tried this

var3="$("echo " $var2 +3 " |bc)"
vigneshhegde
  • 67
  • 1
  • 8
  • Seriously? That should break, because you are trying to run a command named `echo `, not `echo`. – chepner Dec 18 '15 at 21:18
0

You are missing parenthesis

var2=$(cat "file")
var3=$(( var2 + 3 ))
echo $var3

Also you can try with expr Something like this

var2=$(cat "filename")
var3=`expr $var2 + 3`
echo $var3

Here is a good answer HIH

Community
  • 1
  • 1
antorqs
  • 619
  • 3
  • 18
  • The code the OP has should be working fine. Replacing the sub-shell, pipe and invocation of `bc` by using the shells arithmetic expansion (i.e. `$((...))`) is a good idea but not a material distinction in terms of "fixing" the problem. – Etan Reisner Dec 18 '15 at 12:29
  • It's actually a bad idea if `var2`, as it seems from the OP's comment, has a floating-point value. – chepner Dec 18 '15 at 21:18