LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How do I pass multiple parameters? Is there a possibility? (https://www.linuxquestions.org/questions/linux-newbie-8/how-do-i-pass-multiple-parameters-is-there-a-possibility-4175547056/)

vamshi krishna 07-02-2015 02:31 PM

How do I pass multiple parameters? Is there a possibility?
 
So I'm a newbee to Unix Programming.
I've been reading the unix shell programming by Kochen & Wood lately. I know how to pass parameters in command line.
Example: sh display.sh vamshi krishna


Code:
echo " your name is $1 $2 "

But what if write a code using functions to do an operation and we dont know how many arguments can be passed by the user.

Example: the user wants to add 2 numbers at a time.
. add.sh
sum 5 6
This should give him 11 as output



Now what if the user wants to add 4 numbers?
example: add.sh
sum 1 2 3 4
This should give the output 10


So is there a way we can do addition of any number of numbers with a single program? Help will be appreciated

Thanks

grail 07-02-2015 02:42 PM

Look in your book for special characters. Currently you have used '$' to return the value of a single variable / parameter. There will be a section explaining what special character contains
all parameters passed to a script / function.

vamshi krishna 07-02-2015 03:28 PM

@grail I have read that section already. I didnt find anything useful. Thats why I've posted it here.
can a function accommodate single or multiple augments? Is it really possible??

sh add.sh
sum 4 54 34 234 645 234 234
Possible???

suicidaleggroll 07-02-2015 03:43 PM

$1 will get you the first argument, $2 will get you the second, etc.
$# will tell you how many arguments there are
$@ will grab all of the arguments

You can also use "shift" to shift the arguments by one, eg:
echo $1
shift
echo $1
shift
echo $1

Will print out the first three arguments.

Stick it in a while loop using $# and keep adding $1 to the sum and you can add as many numbers as you want.

grail 07-02-2015 09:00 PM

Information provided above is what you need and if the book you have has nothing about $@ in it I would suggest getting a new book as that one is flawed.


All times are GMT -5. The time now is 06:42 PM.