LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   pass arguments and return values from a function in UNIX (https://www.linuxquestions.org/questions/programming-9/pass-arguments-and-return-values-from-a-function-in-unix-654508/)

gaynut 07-09-2008 02:38 AM

pass arguments and return values from a function in UNIX
 
hi,

is it possible to pass arguments and get return values from a function in UNIX ,as we do in C , ?

Incase, yes, then how should i write my function?


thanks,
~ gaynut

matthewg42 07-09-2008 03:19 AM

What do you mean by "in unix"? Shell scripting?

gaynut 07-09-2008 05:55 AM

yes, shell scripting.

matthewg42 07-09-2008 06:24 AM

Yes you can pass arguments in borne style shells like bash. For example:
Code:

#!/bin/bash

my_func () {
    echo "my_func number of arguments: $#"
    echo "my_func arg 1 is $1"
    echo "my_func arg 2 is $2"
    echo "my_func arg 3 is $3"
    echo "my_func arg 4 is $4"
    echo "my_func arg 5 is $5"
}

my_func hello there bob

The return value is a little different - it must be an integer between 0 and 255, and is assigned to $? when the function returns. For example:
Code:

#!/bin/bash

random_0_to_3 () {
    return $(($RANDOM % 4))
}

for ((i=0; i<5; i++)); do
    random_0_to_3
    echo "return value was $?"
done

In general, the return value is only used to determine success or failure of the function, in the same way you'd use the value of $? after calling a regular shell command.

If you want your function to produce some output which can then be used, you can use stdout, and run the command with the $() syntax. For example:
Code:

#!/bin/bash

quantity_description () {
    if  [ $1 -ge 4 ]; then echo "a lot of beaks to feed"
    elif [ $1 -eq 3 ]; then echo "quite a few beady eyes staring at me"
    elif [ $1 -ge 2 ]; then echo "a pair of them"
    elif [ $1 -eq 1 ]; then echo "just one, all on his lonesome"
    elif [ $1 -eq 0 ]; then echo "none at all"
    fi
}

for ((i=0; i<10; i++)); do
    number=$((RANDOM % 6))
    echo "I have $number penguins, which makes $(quantity_description $number)"
done


gaynut 07-10-2008 02:56 AM

thank u for the clear explanation.


All times are GMT -5. The time now is 03:05 AM.