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?
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With