17

I tried to print the value returned from testfunction. But it is not displaying anything . I used ./filename.sh to execute the script. Please help

#!/bin/ksh
testfunction()
{

k=5

return $k

}

val=$(testfunction)

echo  $val

3 Answers 3

36

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 5
echo $val  # prints 3
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

-3

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_Address
exit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.