gpt4 book ai didi

linux - 如何将函数的输出分配给 bash 中的变量?

转载 作者:太空宇宙 更新时间:2023-11-04 10:38:52 24 4
gpt4 key购买 nike

这已经讨论过了,但我有一个更不同的问题:我有一个函数需要用 $@ 作为参数调用。

如果我输入 var=$(function $@),我只会在函数操作的每一行收到错误。

同时我使用了一个变通方法:

  1. 我先调用了函数:function $@
  2. 然后我将函数的结果存储到变量中:var=$?

但这只在函数返回“成功”或“失败”时有效。有什么想法吗?

代码:

function()
{
if [ $1 -gt $x ]
then
return 0
fi

if [ $1 -eq $x ]
then
return 1
fi

if [ $1 -lt $x ]
then
return 2
fi
}

我想将 0、1 或 2 存储在我的变量中。为此:

menu ()
{
if [ $# -gt 5 ] || [ $# -lt 1 ]
then
echo "Error! Script is: " $0
return
fi

echo "Insert reference number: "
read x

while [ $# -gt 0 ]
do
rez=$(function $@)

if [ $rez -eq 0 ]
then
echo "Nr >!" $1
fi

if [ $rez -eq 1 ]
then
echo "Nr =!" $1
fi

if [ $rez -eq 2 ]
then
echo "Nr <!" $1
fi
shift
done
}

最佳答案

  1. 可以使用 elif,这样您就不会收到返回的多个值(另外,case 语句可能是更好的解决方案)。

  2. var=$(function $@ >/dev/null 2>&1; echo $?) 应该做你想做的,我相信?

关于linux - 如何将函数的输出分配给 bash 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36112583/

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