在shell脚本中从调用函数返回值

我想从shell脚本中调用的函数返回值。 也许我错过了语法。 我尝试使用全局variables。 但是这也不起作用。 代码是:

lockdir="somedir" test() { retval="" if mkdir "$lockdir" then # Directory did not exist, but it was created successfully echo >&2 "successfully acquired lock: $lockdir" retval="true" else echo >&2 "cannot acquire lock, giving up on $lockdir" retval="false" fi return retval } retval=test() if [ "$retval" == "true" ] then echo "directory not created" else echo "directory already created" fi 

Bash函数不能像你想要的那样直接返回一个string。 你可以做三件事情:

  1. 回声一个string
  2. 返回一个退出状态,这是一个数字,而不是一个string
  3. 共享一个variables

其他一些炮弹也是如此。

以下是如何执行这些选项的方法:

1.回声串

 lockdir="somedir" testlock(){ retval="" if mkdir "$lockdir" then # Directory did not exist, but it was created successfully echo >&2 "successfully acquired lock: $lockdir" retval="true" else echo >&2 "cannot acquire lock, giving up on $lockdir" retval="false" fi echo "$retval" } retval=$( testlock ) if [ "$retval" == "true" ] then echo "directory not created" else echo "directory already created" fi 

2.退出退出状态

 lockdir="somedir" testlock(){ if mkdir "$lockdir" then # Directory did not exist, but was created successfully echo >&2 "successfully acquired lock: $lockdir" retval=0 else echo >&2 "cannot acquire lock, giving up on $lockdir" retval=1 fi return "$retval" } testlock retval=$? if [ "$retval" == 0 ] then echo "directory not created" else echo "directory already created" fi 

3.分享variables

 lockdir="somedir" retval=-1 testlock(){ if mkdir "$lockdir" then # Directory did not exist, but it was created successfully echo >&2 "successfully acquired lock: $lockdir" retval=0 else echo >&2 "cannot acquire lock, giving up on $lockdir" retval=1 fi } testlock if [ "$retval" == 0 ] then echo "directory not created" else echo "directory already created" fi 

你工作太辛苦了 您的整个脚本应该是:

如果mkdir $ lockdir 2> / dev / null; 然后 
  回声锁获得
其他
  回声无法获取锁>&2
科幻

但即使这样也许太冗长了。 我会编码它:

 mkdir $ lockdir || 出口1

但由此产生的错误信息有点模糊。

如果只是一个真/假testing,你的函数return 0成功, return 1失败。 testing将是:

 if function_name; then do something else error condition fi 

我认为为失败(glenn jackman)返回0 for succ / 1,而olibre的明确和解释性的答案是这样说的; 只是对结果不是二进制的情况提到一种“组合”方法,而你更喜欢设置一个variables而不是“回显”结果(例如,如果你的函数也是回声的话,这个方法将会不行)。 然后怎样呢? (以下是Bourne Shell)

 # Syntax _w (wrapReturn) # arg1 : method to wrap # arg2 : variable to set _w(){ eval $1 read $2 <<EOF $? EOF eval $2=\$$2 } 

在(是的,这个例子有点傻,它只是一个例子)

 getDay(){ d=`date '+%d'` [ $d -gt 255 ] && echo "Oh no a return value is 0-255!" && BAIL=0 # this will of course never happen, it's just to clarify the nature of returns return $d } dayzToSalary(){ daysLeft=0 if [ $1 -lt 26 ]; then daysLeft=`expr 25 - $1` else lastDayInMonth=`date -d "`date +%Y%m01` +1 month -1 day" +%d` rest=`expr $lastDayInMonth - 25` daysLeft=`expr 25 + $rest` fi echo "Mate, it's another $daysLeft days.." } # main _w getDay DAY # call getDay, save the result in the DAY variable dayzToSalary $DAY