Under the circumstances of your question, m
gets the value hello
in both functions.
Now look at
test -z "$m" && return 1
What should happen here? The -z
test is false, right? So return 1
does not execute. Instead, what does the function return? Every function returns the value of $?
at the end. In this case, that value is 1, the result of the &&
list.
What you might have wanted to test is
if [ -z "$m" ]; then return 1; fi
compared to
if test -z "$m"; then return 1; fi
The exit status of both these if
statements are zero when $m
is non-empty, since none of the statements' branches were taken.
From the POSIX standard:
The exit status of the if
command shall be the exit status of the then
or else
compound-list that was executed, or zero, if none was executed.
Note that we may condense both your functions down into
is_match () {
grep -q -F -e "$1" file.txt
}
Here, we let grep
provide the exit status to the caller. We also do not necessarily read the file.txt
file to the end, as grep -q
quits as soon as it finds a match.