gpt4 book ai didi

bash - 无法访问bash括号内的变量

转载 作者:行者123 更新时间:2023-12-04 19:41:20 26 4
gpt4 key购买 nike

在 bash 中,如果我运行

(foo=14)

然后尝试稍后在我的 bash 脚本中引用该变量:
echo "${foo}"

我什么也得不到。我怎样才能让 bash 以我需要的方式存储这个变量?

具体来说,我在 if 语句中使用它并检查退出代码,类似于:
if (bar="$(foo=14;echo "${foo}"|tr '1' 'a' 2>&1)")
then
echo "Setting "'$bar'" was a success. It is ${bar}"
else
echo "Setting "'$bar'" failed with a nonzero exit code."
fi

最佳答案

括号中的命令,例如()在子shell中执行。子 shell 中的任何分配都不会存在于该子 shell 之外。

foo=14
bar=$(echo $foo | tr '1' 'a' )
if [[ $? -eq 0 ]]
then
echo "Setting "'$bar'" was a success. It is ${bar}"
else
echo "Setting "'$bar'" failed with a nonzero exit code."
fi

关于bash - 无法访问bash括号内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60763887/

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