gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:39:13 25 4
gpt4 key购买 nike

我想从 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 函数无法像您希望的那样直接返回字符串。您可以做三件事:

  1. 回显字符串
  2. 返回退出状态,它是一个数字,而不是字符串
  3. 共享变量

对于其他一些 shell 也是如此。

以下是执行每个选项的方法:

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。共享变量

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

关于shell - 从 shell 脚本中调用的函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8742783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com