Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value in a Bash function

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?

like image 234
mindia Avatar asked Jun 27 '13 07:06

mindia


People also ask

How does a shell function return a value?

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.

What does [- Z $1 mean in bash?

$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.

Can a bash function return a string?

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.

What is the return command in bash?

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.


2 Answers

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.

like image 53
tamasgal Avatar answered Oct 01 '22 12:10

tamasgal


$(...) 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 } 
like image 33
Ignacio Vazquez-Abrams Avatar answered Oct 01 '22 14:10

Ignacio Vazquez-Abrams