Assign the returned value of a function to a variable‎ in unix shell script Assign the returned value of a function to a variable‎ in unix shell script shell shell

Assign the returned value of a function to a variable‎ in unix shell script


The value returned by the function is stored in $?, and is not captured by $().

In other words:

testFunction() {     k=5    echo 3    return $k }val=$(testFunction)echo $? # prints 5echo $val  # prints 3


What you are trying to do will capture the last value 'echoed' in your function in val variable

val=$(testFunction)

If you want to capture return value of your function then you should utilize $? [i.e. echo $?] which is last exit status.


This ksh functions works:

IPADDRESS()     # get the IP address of this host{    # purpose: to get the IP address of this host    #       and return it as a character string    #    typeset -l IPADDR    IPADDR=$(ifconfig -a | grep inet | grep -v '127.0.0.1' | awk '{print $2}')    print $IPADDR}IP_Address=$(IPADDRESS)echo $IP_Addressexit