I'm writing a simple shell script that should exit with 0 if an input string is found in a file, and exit with 1 if it isn't
INPSTR=$1
cat ~/file.txt | while read line
do
if [[ $line == *$INPSTR* ]]; then
exit 0
fi
done
#string not found
exit 1
What's actually happening is that when the string is found, the loop exits, and the shell then goes to "exit 1". What's the correct way to exit from the shell script entirely while in a loop?
You need to avoid creating sub-shell in your script by avoiding the pipe and un-necessary cat
:
INPSTR="$1"
while read -r line
do
if [[ $line == *"$INPSTR"* ]]; then
exit 0
fi
done < ~/file.txt
#string not found
exit 1
Otherwise exit 0
is only exiting from the sub-shell created by pipe and later when loop ends then exit 1
is used from parent shell.
you can catch return code of subshell using $? like this
INPSTR=$1
cat ~/file.txt | while read line
do
if [[ $line == *$INPSTR* ]]; then
exit 0
fi
done
if [[ $? -eq 0 ]]; then
exit 0
else
#string not found
exit 1
fi
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