Can't access variables inside parenthesis in bash

不打扰是莪最后的温柔 提交于 2021-02-17 03:01:27

问题


In bash, if I run

(foo=14)

And then try to reference that variable later on in my bash script:

echo "${foo}"

I don't get anything. How can I make bash store this variable the way I need it to?

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

回答1:


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


来源:https://stackoverflow.com/questions/57411130/cant-access-variables-inside-parenthesis-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!