1

Here's what I'm trying to make: $echo 1 3 5 7 9 | sh test which outputs 25. (final goal is a derivative calculator, don't laugh at me, I'm only grade 12).

When the amount of variables are given, it's pretty easy. But what if you don't know how many variables are there, how do I take everything behind echo, in this case 1 3 5 7 9, and put them into something similar to an array in Java, then simply do something like for i in array and i+=1?

This was my idea:use cat $* to read all numbers, then use while loop to go through all the numbers, and add them to the sum.

Alternate idea: replace all spaces with \n after cat $* then echo it to some file, and use something similar File Reader -> read line in Java for the while loop.

Here's what I don't understand about shell, when you cat $*, do you assign it to something, like a=cat $* and get value by a[0]? and when you do the while loop, do you while read a or what do you while about?

First time posting here, self learning is much harder than I thought..

Thanks for helping!

chenchen
  • 49
  • 3
  • 6
  • 1
    I recommend reading a good tutorial, such as the [BashGuide](http://mywiki.wooledge.org/BashGuide); see list of tutorials [here](http://wiki.bash-hackers.org/scripting/tutoriallist). – Benjamin W. Feb 05 '16 at 06:58
  • Possible duplicate of [How can I quickly sum all numbers in a file?](http://stackoverflow.com/questions/2702564/how-can-i-quickly-sum-all-numbers-in-a-file) – David C. Rankin Feb 05 '16 at 08:23
  • See also: [**Add numbers from file and standard input (duplicate)**](http://stackoverflow.com/questions/35096253/add-numbers-from-file-and-standard-input) – David C. Rankin Feb 05 '16 at 08:23

2 Answers2

1

For example I have test.sh script that contains:

Note: $@ holds all the parameters you will include as you run the script. There's no limit for that. Then iterate it.

#!/bin/bash
ctr=0

for num in "$@"; do
ctr=$[ctr + num]
done
echo "$ctr"

If I'm going to run it like:

./test.sh 1 2 3 4 5

It will give an output of 15. Is that want you want to accomplished?

aldrien.h
  • 3,437
  • 2
  • 30
  • 52
1

A UNIX shell is an environment from which to manipulate (create/move/destroy) files and processes and sequence calls to tools. While the shell language can be coerced to do more than that, the end result if you do so is always worse than if you simply use the right tool for the job. In this case you could use the standard (i.e. available on all UNIX systems), general purpose UNIX text processing tool awk:

$ cat tst.sh
awk '{ for (i=1;i<=NF;i++) tot+=$i; print tot }'

$ echo '1 3 5 7 9' | tst.sh
25

$ echo '1.5 3.14' | tst.sh      
4.64

Read the book Effective Awk Programming, 4th Edition, by Arnold Robbins.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185