Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 896
Anand Tomi Avatar asked Oct 16 '12 16:10

Anand Tomi


People also ask

How do I return a value from one shell script to another shell?

The construct var=$(myfunction) captures the standard out from myfunction and saves it in var . Thus, when you want to return something from myfunction , just send it to standard, like we did with echo in the example above.

How do I assign a value to a variable in bash?

To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore.


1 Answers

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
like image 174
William Pursell Avatar answered Oct 25 '22 18:10

William Pursell