Reputation: 2639
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?
Upvotes: 15
Views: 21198
Reputation: 1385
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
Upvotes: 7
Reputation: 33327
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)
Upvotes: 19