【问题标题】:Shell - Variable scope and assignment [duplicate]Shell - 变量范围和分配[重复]
【发布时间】:2014-02-02 04:10:02
【问题描述】:

我很好奇为什么在以下代码中对变量“nameExists”的赋值没有按预期工作:

        nameExists=1
        cat $dataFile | while read line
        do
            lineName=${line%%:*}
            if [ "$lineName" == "$name" ]
            then
                echo "The entry you are trying to add already exists!"
                nameExists=0
                break
            fi
        done

        if [ $nameExists -eq 1 ]
        then
            echo "Append here."
        fi

我发现,无论我是否达到内部赋值“nameExists=0”,$nameExists 的值始终为 1。我想知道这是否是因为 do 循环内的 nameExists 变量被视为本地变量多变的。如果是这样,我将如何声明 nameExists 变量或分配给 nameExists 变量,以便在分配后保持 0 的值。

【问题讨论】:

  • 你打开了shell调试/跟踪功能吗? set -vx 将显示下一个要执行的块和语句,然后在每行执行时在前面带有 + 符号,并用值替换变量。偶尔的 shellism(例如将大多数字符串更改为单引号字符串以及使用其他标准化符号)可能会混淆问题,因此请关注变量的值并假设 -vx 选项对您的字符串做正确的事情。祝你好运。

标签: shell variables unix scope variable-assignment


【解决方案1】:

我的问题的答案相对简单,从这里的文章中收集到:http://mywiki.wooledge.org/BashFAQ/024

通过管道命令引入新的SubShell,

cat $dataFile | 

我随后介绍了一个特定于 Subshel​​l 的新变量上下文和环境。因此,我的赋值“nameExists=0”在循环内被限定在本地范围内,并且在 Subshel​​l 完成执行后不会持续存在。我通过删除不必要的管道解决了这个问题。我生成的代码按预期工作,如下所示。

    nameExists=1
    while read -r line
    do
          lineName=${line%%:*}
          if [ "$lineName" == "$name" ]
          then
              echo "The entry you are trying to add already exists!"
              nameExists=0
              break
          fi
    done < $dataFile

    if [ $nameExists -eq 1 ]
    then
        echo "Append here."
    fi

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 2012-12-28
    • 2013-11-10
    • 2012-08-21
    • 2010-09-13
    • 1970-01-01
    相关资源
    最近更新 更多