【问题标题】:Getting variable from inside while loop从while循环内部获取变量
【发布时间】:2013-06-19 14:38:01
【问题描述】:

我有一个收集有关文件子目录的信息的脚本。我正在检查文件创建之间的时间是否一致。

last=0
LOGCHECK="YES"
ls -l /dir/*.log | gawk '{print $8}' | sed s/:/*60+/g | bc |
        while read fname
        do
            current=$fname
            if [ $last = 0 ]; then
                last=$current
            elif [ $((current - last)) -ne 1 ]; then
                echo "Time difference discrepancy: $((current - last)) minute(s) is not expected"
                LOGCHECK="NO"
                last=$current    
            else
                last=$current
            fi      
        done

仅当 .log 文件创建之间的时间不是一分钟时才会输出。我的问题是,while 循环中的 $LOGCHECK 位于另一个我相信来自管道的子 shell 中?

有没有办法获取这个变量信息?

【问题讨论】:

    标签: bash variables pipe


    【解决方案1】:

    这是bash 脚本的常见情况。像这样重组你的循环:

    while read fname
    do
      # stuff
    done < <(ls -l /dir/*.log | gawk '{print $8}' | sed s/:/*60+/g | bc)
    

    然后在循环中设置的变量在之后仍然可用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2012-06-01
      相关资源
      最近更新 更多