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
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With