I am working with a bash script and I want to execute a function to print a return value:
function fun1(){ return 34 } function fun2(){ local res=$(fun1) echo $res }
When I execute fun2
, it does not print "34". Why is this the case?
A function may return a value in one of four different ways: Change the state of a variable or variables. Use the exit command to end the shell script. Use the return command to end the function, and return the supplied value to the calling section of the shell script.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
Bash function can return a string value by using a global variable. In the following example, a global variable, 'retval' is used. A string value is assigned and printed in this global variable before and after calling the function. The value of the global variable will be changed after calling the function.
return command is used to exit from a shell function. It takes a parameter [N], if N is mentioned then it returns [N] and if N is not mentioned then it returns the status of the last command executed within the function or script.
Although Bash has a return
statement, the only thing you can specify with it is the function's own exit
status (a value between 0
and 255
, 0 meaning "success"). So return
is not what you want.
You might want to convert your return
statement to an echo
statement - that way your function output could be captured using $()
braces, which seems to be exactly what you want.
Here is an example:
function fun1(){ echo 34 } function fun2(){ local res=$(fun1) echo $res }
Another way to get the return value (if you just want to return an integer 0-255) is $?
.
function fun1(){ return 34 } function fun2(){ fun1 local res=$? echo $res }
Also, note that you can use the return value to use Boolean logic - like fun1 || fun2
will only run fun2
if fun1
returns a non-0
value. The default return value is the exit value of the last statement executed within the function.
$(...)
captures the text sent to standard output by the command contained within. return
does not output to standard output. $?
contains the result code of the last command.
fun1 (){ return 34 } fun2 (){ fun1 local res=$? echo $res }
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