Bash脚本在“ if”之后丢失变量(简单的#bash代码)

三亚斯奈克斯

为什么变量$ c在代码末尾不回显“微笑”,而仅回显空值?

在“如果运算符”结束后,我不会获得变量$ c,但是当运算符完成作业时,我的值$ c不会返回“微笑”,而只会返回“”(空值)

#!/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 ~]#
约翰·库格曼

摆脱括号。括号创建子外壳,并且在子外壳中设置的变量不会传播回父外壳。

if [ "$a" != "$b" ]; then
    c="smile"
    echo "echo inside if:"
    echo $c  # in this echo "smile" 
else
    c="yes" 
fi

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章