Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash exit doesn't exit

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

I have two files:

file1.txt with the following content:

aaaaaa
bbbbbb
cccccc
dddddd
eeeeee
ffffff
gggggg

file2.txt with the following content:

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.

#!/bin/bash
path=`dirname $0`

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 !!!!!!!!!!:

aaaaaa
!!!!!!!!!!
bbbbbb
cccccc
dddddd
eeeeee
ffffff
!!!!!!!!!!
gggggg

Isn't exit supposed to end the execution of the script altogether?

like image 757
Tulains Córdova Avatar asked Aug 21 '13 14:08

Tulains Córdova


2 Answers

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

#!/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

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

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)
like image 137
user000001 Avatar answered Nov 13 '22 12:11

user000001


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

            ...
            echo "!!!!!!!!!!"
            exit 1
        fi
    done
    [ $? == 1 ] && exit 0;
done
like image 33
svante Avatar answered Nov 13 '22 11:11

svante