Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exiting a shell script from inside a while loop

Tags:

linux

shell

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?

like image 716
user2824889 Avatar asked Apr 10 '15 15:04

user2824889


2 Answers

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.

like image 198
anubhava Avatar answered Oct 24 '22 11:10

anubhava


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
like image 20
Allien Avatar answered Oct 24 '22 12:10

Allien