如何在此脚本中打破无限循环

时间:2014-05-31 11:15:25

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

我正在用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 :循环?

谢谢

1 个答案:

答案 0 :(得分: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