代码之家  ›  专栏  ›  技术社区  ›  africandrogba

在shell脚本中,在while循环中读取文件后无法访问外部变量

  •  0
  • africandrogba  · 技术社区  · 7 年前
    #!/bin/sh
    # Read in classpath
    if [ x"${JAVA_CLASSPATH}" != x ]; then
        classpath="${JAVA_CLASSPATH}"
    else
        classpath=""
        while read file; do
            classpath="${classpath}:${JAVA_APP_DIR}/lib/$file"
        done < ${JAVA_APP_DIR}/lib/classpath
    fi
    echo classpath is ${classpath}
    

    echo : classpath is 
    

    PS:我看到了其他类似的问题,我没有使用这些问题中提到的任何管道。我的代码反映了这些问题的答案,但我仍然面临着这个问题。这也是一个shell脚本,而不是bash。

    1 回复  |  直到 7 年前
        1
  •  0
  •   agc Blair Houghton    7 年前

    最有可能 ${JAVA_APP_DIR}/lib/classpath 不存在。

    比较以下两个相似的代码位(只有第一行不同),在 POSIX公司 dash 外壳:

    1. dummyfile文件

      echo baz > dummyfile
      unset foo
      if false
      then : 
      else while [ -z "$foo" ] ; do
               foo="bar"
           done < dummyfile
      fi
      echo "=$foo="
      

      输出:

      =bar=
      
    2. dummyfile文件 不存在。

      rm -f dummyfile
      unset foo
      if false
      then : 
      else while [ -z "$foo" ] ; do
               foo="bar"
           done < dummyfile
      fi
      echo "=$foo="
      

      dash: 65: cannot open dummyfile: No such file
      ==
      

      文件的内容 while 循环从未运行过。


    请注意,代码有点奇怪:

    • 这个 循环始终运行 一旦 还有出口,因为 $foo unset 然后重置。

    • 有一个 done < dummyfile ,但不是 read 从中输入任何信息。但即使没有 命令,该文件的存在,结合 < $富 已设置。

    • 即使是空文件也可以:

      unset foo
      if false
      then : 
      else while [ -z "$foo" ] ; do
               foo="bar"
           done < /dev/null
      fi
      echo "=$foo="
      
    推荐文章