陷入无限循环

时间:2017-12-06 10:57:37

标签: bash while-loop increment

我正在尝试编写此代码,以便在进程读取管道中的map完成时,它会将变量递增1,以便最终突破while循环。否则,它将向密钥文件添加唯一参数。然而,它进入一个无限循环,永远不会脱离循环。

while [ $a -le 5 ]; do
    read input < map_pipe;
    if [ $input = "map finished" ]; then
            ((a++))
            echo $a
    else
            sort -u map_pipe >> keys.txt;
    fi
done

1 个答案:

答案 0 :(得分:0)

我决定为你解决这个问题,不确定这是不是你想要的,但我认为我很接近:

#!/bin/bash
a=0 #Initialize your variable to something
while [ $a -le 5 ]; do
    read input < map_pipe;
    if [ "$input" = "map finished" ]; then #Put double quotes around variables to allow values with spaces
        a=$(($a + 1)) #Your syntax was off, use spaces and do something with the output
    else
        echo $input >> keys.txt #Don't re-read the pipe, it's empty by now and sort will wait for the next input
        sort -u keys.txt > tmpfile #Instead sort your file, don't save directly into the same file it will break
        mv tmpfile keys.txt
        #sort -u keys.txt | sponge keys.txt #Will also work instead of the other sort and mv, but sponge is not installed on most machines
    fi  
done