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
3
  • 1
    So whats wrong with the code? Can anyone show me the code with a for loop? please. Commented Aug 12, 2015 at 2:48
  • Not really. I don't need to add fractions just integers. Commented Aug 12, 2015 at 3: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 ;-) Commented Aug 12, 2015 at 3:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.