Weird Exit Status of shell script

I have a script named check which will read the content of a file and check wether those files exist in the current directory. If so it will have the exit status of 0, otherwise it will have 1.
check script:

#!/bin/bash
if [ $# -lt 1 ] ; then #Check there is enough command line parameters.
        exit 1
fi

cat $1 | while read i; do #Check whether there is missing file
        `[ -e $i ]`
        if [ $? != 0 ] ; then
                exit 1
        fi
done

exit 0

Now I have a file named suite.txt whose content is

test1
test2
test3

In current directory, there are only test1 and test2 exist, however, test3 doesn't.
When executing

./check suite.txt; echo $?

It gave the 0 which means that there was no missing files. I feel so confused about that. Any ideas?
Thanks in advance!

It is due to the fact that you are using a pipeline.

To see the difference, change your code to:

#!/bin/bash

if [ $# -lt 1 ] ; then #Check there is enough command line parameters.
        exit 1
fi

while read i
do
        `[ -e $i ]`
        if [ $? != 0 ] ; then
             exit 1
        fi
done < $1

exit 0

By the way, your if expression would be better written as:

while read i
do
     if  [ ! -e $i ]
     then
         exit 1
     fi
done < $1
1 Like

In bash , the piped processes run in sub-shells. So, the second exit 1 is only affecting the sub-shell running the while loop and not your whole script.

Try a variant such as:

...
while read i; do
 `[ -e "$i" ]`
 if [ $? != 0 ] ; then
 exit 1
 fi
done < "$1"
...

Also, the command substitution is an overkill here:

...
while read i; do
 [ -e "$i" ] || exit 1
done < "$1"
...
1 Like