无法在bash中的括号内访问变量 [英] Can't access variables inside parenthesis in bash
本文介绍了无法在bash中的括号内访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在bash中,如果我跑步
In bash, if I run
(foo=14)
然后稍后在我的bash脚本中尝试引用该变量:
And then try to reference that variable later on in my bash script:
echo "${foo}"
我什么都没得到.如何让bash像我需要的那样存储此变量?
I don't get anything. How can I make bash store this variable the way I need it to?
具体来说,我在if语句中使用此代码并检查退出代码,例如:
Specifically, I am using this in an if statement and checking the exit code, something kind of like:
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
推荐答案
括号中的命令,例如()
在子外壳中执行.子外壳中的任何分配都不会存在于该子外壳之外.
Commands enclosed in parenthesis e.g. ()
are executed in a sub-shell. Any assignment in a sub-shell will not exist outside that sub-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中的括号内访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文