Bash 退出不退出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18359777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:20:05  来源:igfitidea点击:

Bash exit doesn't exit

bashexitnested-loopsabort

提问by Tulains Córdova

I wonder why this script continues to run even with an explicit exit command.

我想知道为什么即使使用显式退出命令,该脚本仍会继续运行。

I have two files:

我有两个文件:

file1.txtwith the following content:

file1.txt具有以下内容:

aaaaaa
bbbbbb
cccccc
dddddd
eeeeee
ffffff
gggggg

file2.txtwith the following content:

file2.txt具有以下内容:

111111
aaaaaa
222222
333333
ffffff
444444

The script (test.sh) is this, two nested loops checking if any line of the first file contains any line of the second file. If it finds a match, it aborts.

脚本 ( test.sh) 是这样的,两个嵌套循环检查第一个文件的任何行是否包含第二个文件的任何行。如果找到匹配项,则中止。

#!/bin/bash
path=`dirname 
aaaaaa
!!!!!!!!!!
bbbbbb
cccccc
dddddd
eeeeee
ffffff
!!!!!!!!!!
gggggg
` cat $path/file1.txt | while read line do echo $line cat $RUTA/file2.txt | while read another do if [ ! -z "`echo $line | grep -i $another`" ]; then echo "!!!!!!!!!!" exit 0 fi done done

I get the following output even when it should exit after printing the first !!!!!!!!!!:

即使在打印第一个后应该退出,我也会得到以下输出!!!!!!!!!!

#!/bin/bash

while read -r line
do
    echo "$line"
     while read -r another
    do
        if  grep -i "$another" <<< "$line" ;then
            echo "!!!!!!!!!!"
            exit 0
        fi
    done < file2.txt
done < file1.txt

Isn't exitsupposed to end the execution of the script altogether?

exit应该完全结束脚本的执行吗?

回答by user000001

The reason is that the pipes create sub processes. Use input redirection instead and it should work

原因是管道创建了子进程。改用输入重定向,它应该可以工作

while read -r line
do
    echo "$line"
     while read -r another
    do
        if  grep -i "$another" <<< "$line" ;then
            echo "!!!!!!!!!!"
            exit 0
        fi
    done < <(command2)
done < <(command1)

In the general case, where the input comes from another program and not from a file, you can use process substitution

在一般情况下,输入来自另一个程序而不是来自文件,您可以使用进程替换

            ...
            echo "!!!!!!!!!!"
            exit 1
        fi
    done
    [ $? == 1 ] && exit 0;
done

回答by svante

The while loops are running in their respective shells. Exiting one shell does not exit the containing ones. $? could be your friend here:

while 循环在各自的 shell 中运行。退出一个外壳不会退出包含的外壳。$? 可能是你的朋友:

##代码##