shell正常循环时无法退出。

时间:2017-12-08 12:42:13

标签: shell if-statement while-loop

$ cat Judge_file.sh
#!/bin/bash
i=1
while [ $i ];do
    read -p "Enter your MO or attribute name: " name
    if [ $name = "q" ];then
        i=0
        continue
    else
        grep -q $name *.txt    #check character existence in currently directory of all .txt file
        if [ $? -eq 0 ];then
            echo "Name exists,send to file 2"
            echo $name >> 2.txt
        else
            echo "Name missing,send to file 1"
            echo $name >> 1.txt
        fi
    fi
done
$ . ./Judge_file.sh
Enter your MO or attribute name: chenghuang
Name exists,send to file 2
Enter your MO or attribute name: llkk
Name missing,send to file 1
Enter your MO or attribute name: q
Enter your MO or attribute name: q
Enter your MO or attribute name: q

这是一个判断角色存在的程序。

当我输入“q”时,应该退出。但为什么它仍然让我输入。

当我将while [ $i ]验证为while [ 0 ]时,有一件事真的很奇怪,然后while循环仍让我输入,直到我输入Ctrl + c退出。

1 个答案:

答案 0 :(得分:1)

我会选择脚本的重要部分来解决问题:

相反:

...
if [ $name = "q" ];then
    i=0
    continue
else
...

你应该:

...
if [ $name = "q" ];then
    i=0
    break
else
...

然后,当您按下q键时脚本将终止。

continue继续循环结束。如果要终止while循环,则必须使用break

首次修改
根据评论,我认为你误解了bash []的含义。

while [0]tests 0相同。这总是正确的,从而导致无休止的循环。

我真的建议使用true / false而不是1/0。要使用continue重写代码:

#!/bin/bash
i=true
while $i;do
    read -p "Enter your MO or attribute name: " name
    if [ $name = "q" ];then
        i=false
        continue
    else
        grep -q $name *.txt    #check character existence in currently directory of all .txt file
        if [ $? -eq 0 ];then
            echo "Name exists,send to file 2"
            echo $name >> 2.txt
        else
            echo "Name missing,send to file 1"
            echo $name >> 1.txt
        fi
    fi
done

如果您坚持使用1/0,则可以按照以下步骤进行操作

#!/bin/bash
i=1
while (( $i ));do
    read -p "Enter your MO or attribute name: " name
    if [ $name = "q" ];then
        i=0
        continue
    else
        grep -q $name *.txt    #check character existence in currently directory of all .txt file
        if [ $? -eq 0 ];then
            echo "Name exists,send to file 2"
            echo $name >> 2.txt
        else
            echo "Name missing,send to file 1"
            echo $name >> 1.txt
        fi
    fi
done

现在它的行为可能与假设0为假,1为真。