我想从 shell 脚本中调用的函数返回值。也许我错过了语法。我尝试使用全局变量。但这也行不通。代码是:
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 函数不能像您希望的那样直接返回字符串。你可以做三件事:
这也适用于其他一些 shell。
以下是如何执行每个选项:
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
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, 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