码迷,mamicode.com
首页 > 其他好文 > 详细

Returning Values from Bash Functions

时间:2014-12-21 12:41:49      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

  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
}

myfunc
echo $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

标签:

原文地址:http://www.cnblogs.com/lxw0109/p/shell_return_value.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!