我想从shell脚本中调用的函数返回值。也许我缺少语法。我试着使用全局变量。但这也不行。代码是:
lockdir="somedir" test() { retval="" if mkdir "$lockdir" then # directory did not exist,but 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函数不能直接返回一个字符串,就像你想要的。你可以做三件事:
> echo一个字符串
>返回退出状态,这是一个数字,而不是字符串
>共享变量
这对于一些其他壳也是正确的。
以下是执行每个选项的方法:
回声字符串
lockdir="somedir" testlock(){ retval="" if mkdir "$lockdir" then # directory did not exist,but 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
共享变量
lockdir="somedir" retval=-1 testlock(){ if mkdir "$lockdir" then # directory did not exist,giving up on $lockdir" retval=1 fi } testlock if [ "$retval" == 0 ] then echo "directory not created" else echo "directory already created" fi