I tried to create a shell script, which sum the given numbers. If there is no given parameter, then it tries to read the pipe output, but I get an error.
#!/bin/sh
sum=0
if [ $# -eq 0 ]
then
while read data
do
sum=`expr $sum + $data`
done
else
for (( i = 1 ; i <= $#; i++ ))
do
sum=`expr $sum + ${!i}`
done
fi
echo $sum
This works: sum 10 12 13
But this one doesn’t: echo 10 12 13| sum
Thanks in advance,
Here you go (assuming
bash, notsh):You can invoke it thus:
Hope this helps!
Edit. You might also be interested in learning cool stuff about
IFS. I’ve noticed that people tend to confuse@and*inbash. If you don’t know what I’m talking about, then you should use@instead of*, also for array subscripts! In thebashmanual, you’ll find that when double quoted,$*(or${array[*]}) expands to all the elements of the array separated by the value of theIFS. This can be useful in our case:Gniourf now exits from teacher mode.
:-)