1

Just started doing basic shell scripting need some help with adding number for example 6 9 -4 2 with add command

#!/bin/bash


function add() {
sum=`expr $a + $b + $c + $d`
echo "$sum";  }

read a b c d
add

fi
Matt Clark
  • 27,671
  • 19
  • 68
  • 123
gandhifolie
  • 21
  • 1
  • 2
  • 1
    So whats wrong with the code? Can anyone show me the code with a for loop? please. – gandhifolie Aug 12 '15 at 02:48
  • Not really. I don't need to add fractions just integers. – gandhifolie Aug 12 '15 at 03:09
  • does your example data include fractions? Do you mean `1/2`, or `.5` ? Read about `awk` it can help you do these transparently without worry about floating point or integer. `echo '6 9 -4 2 ' | awk '{print tot=$1+$2+$3+$4+0.0}'` (remove the `+0.0` if you need integer addition). Good luck. (misread your comment about fractions, sorry). Good luck again ;-) – shellter Aug 12 '15 at 03:35

1 Answers1

3

Aside of the "fi" at the end of your script (likely a copy-and-paste error?), the script looks correct, although it can be done easier: bash already has the capability to do calculation, so you don't need to create a child process by invoking expr:

echo $((a+b+c+d))

would also output the sum.

user1934428
  • 19,864
  • 7
  • 42
  • 87