为什么代码末尾的变量$ c不回显“微笑”而只回显空值?
在“if运算符”结束后我不会得到变量$ c但是当运算符完成作业时我的值$ c不返回“smile”但只返回“”(空值)
#!/bin/bash
###
## sh example.sh
a="aaa"
b="bbb"
if [ "$a" != "$b" ]; then (
c="smile"
echo "echo inside if:"
echo $c # in this echo "smile"
) else (
c="yes"
) fi
echo "echo after fi:"
echo $c # echo "" # why this not echo "smile"
结果:
[root@my-fttb ~]# sh /folder/example.sh
echo inside if:
smile
echo after fi:
[root@my-fttb ~]#
答案 0 :(得分:6)
摆脱括号。括号创建子shell,子shell中设置的变量不会传播回父shell。
if [ "$a" != "$b" ]; then
c="smile"
echo "echo inside if:"
echo $c # in this echo "smile"
else
c="yes"
fi
答案 1 :(得分:4)
括号如果是if语句,则创建一个子shell,因此父shell中的变量不会改变。
删除括号:
if [ "$a" != "$b" ]; then
c="smile";
echo "echo inside if:"
echo $c; # in this echo "smile"
else
c="yes";
fi