lee*_*oon 4 variables macos bash if-statement
在 bash 中,如果我运行
(foo=14)
Run Code Online (Sandbox Code Playgroud)
然后尝试稍后在我的 bash 脚本中引用该变量:
echo "${foo}"
Run Code Online (Sandbox Code Playgroud)
我什么也没得到。我怎样才能让 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
Run Code Online (Sandbox Code Playgroud)
括号中的命令例如()在子 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
Run Code Online (Sandbox Code Playgroud)