首页 > 代码库 > Returning Values from Bash Functions

Returning Values from Bash Functions

  Bash functions, unlike functions in most programming languages do not allow you to return a value to

the caller. When a bash function ends its return value is its status: zero for success, non-zero for failure.To

return values, you can set a global variable with the result, or use command substitution, or you can pass in

the name of a variable to use as the result variable. The examples below describe these different mechanisms.

  Although bash has a return statement, the only thing you can specify with it is the function‘s status, which

is a numeric value like the value specified in an exit statement. The status value is stored in the $? variable. If

a function does not contain a return statement, its status is set based on the status of the last statement executed

in the function. To actually return arbitrary values to the caller you must use other mechanisms.

  The simplest way to return a value from a bash function is to just set a global variable to the result. Since

all variables in bash are global by default this is easy:

function myfunc(){  myresult=some value}myfuncecho $myresult

  The code above sets the global variable myresult to the function result. Reasonably simple, but as we all

know, using global variables, particularly in large programs, can lead to difficult to find bugs.

  A better approach is to use local variables in your functions. The problem then becomes how do you get

the result to the caller. One mechanism is to use command substitution:

function myfunc(){  local myresult=some value  echo "$myresult"}result=$(myfunc)echo $result

  Here the result is output to the stdout and the caller uses command substitution to capture the value

in a variable. The variable can then be used as needed.

 

摘录自:

Returning Values from Bash Functions: http://www.linuxjournal.com/content/return-values-bash-functions

Returning Values from Bash Functions