【问题标题】:How to break infinite loop in this script如何在此脚本中打破无限循环
【发布时间】:2014-07-21 02:05:58
【问题描述】:

我正在用 bash 做一些有趣的事情

我在下面写了脚本:

#!/bin/bash
while :
do
    if [ -s /tmp/file.txt ]; then
        for line in $(cat /tmp/file.txt)
        do
            echo $line
            #May be some commands here
        done
    fi
done

我的file.txt的内容是:

1 True
2 Flase

如果命令cat /tmp/file.txt 已完成(我的意思是所有行都已读取)并且echo $line 和其他命令已完成然后break 不定式while : 循环,我该如何说脚本?

谢谢

【问题讨论】:

  • 你为什么设置while循环?你可以从这段代码中删除它,它是无用的。只有当你想测试文件的内容是否准备好时,在这种情况下你应该使用sleep 10 来避免你的 CPU 过载
  • 这是必需的,因为有些命令在后台运行。我想说的是,这些命令的 pid 在工作时是无限的

标签: bash loops process while-loop infinite-loop


【解决方案1】:

使用break

#!/bin/bash
while :
do
    if [ -s /tmp/file.txt ]; then
        for line in $(cat /tmp/file.txt)
        do
            echo $line
            #May be some commands here
        done
        break
    fi
done

虽然这样会更简单,更合适:

#!/bin/bash
for (( ;; )); do
    if [[ -s /tmp/file.txt ]]; then
        # Never use `for X in $()` when reading output/input. Using word splitting
        # method for it could be a bad idea in many ways. One is it's dependent with
        # IFS. Second is that glob patterns like '*' could be expanded and you'd
        # produce filenames instead.
        while read line; do
            # Place variables between quotes or else it would be subject to Word
            # Splitting and unexpected output format could be made.
            echo "$line"
        done < /tmp/file.txt
        break
    fi
done

另一方面,你真的需要外循环吗?这次不用break了。

#!/bin/bash
if [[ -s /tmp/file.txt ]]; then
    while read line; do
        echo "$line"
    done < /tmp/file.txt
fi

【讨论】:

  • 是的,因为我在后台运行一些命令。所以我想告诉commands in if [[ -s /tmp/file.txt ]]; then` 在后台的命令有效时运行
  • 如果是这种情况,我建议在循环结束时插入一个 sleep 命令,以避免脚本在不读取文件时占用所有处理能力。
猜你喜欢
  • 2013-03-08
  • 2012-04-02
  • 1970-01-01
  • 2012-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
相关资源
最近更新 更多