【问题标题】:Bash script lose variable after "if" (simple #bash code)Bash 脚本在“if”之后丢失变量(简单的#bash 代码)
【发布时间】:2014-07-12 12:45:12
【问题描述】:

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

在“if operator”结束后我不会得到变量 $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 ~]#

【问题讨论】:

    标签: linux bash shell sh


    【解决方案1】:

    去掉括号。括号创建子 shell,子 shell 中设置的变量不会传播回父 shell。

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

    【讨论】:

      【解决方案2】:

      if语句的括号,创建一个子shell,所以变量在父shell中不会改变。

      去掉括号:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-18
        • 1970-01-01
        • 2021-01-12
        • 2020-09-24
        • 2013-09-02
        • 1970-01-01
        • 1970-01-01
        • 2016-08-24
        相关资源
        最近更新 更多