Since you want to test the exit status of grep
, and you want to see the line if it does not contain xxxx
, you can adapt the following code to suit our requirements (where I'm using echo "$line"
as a surrogate for your command1
, and I'm echoing exit 1
rather than actually exiting when your code would execute exit 1
):
for line in 'hello xxxx here' 'hello yyyy here'
do
if ! echo "$line" | grep -v 'xxxx'
then echo "exit 1"
fi
done
The output is:
exit 1
hello yyyy here
See How can I negate the return value of a process? for a discussion of the !
operator in POSIX shells (such as Bash).
Since you don't want to see the output when it contains xxxx
but do otherwise, the -v
option to grep
inverts the logic, only printing lines that do not match xxxx
. The status of grep -v 'xxxx'
is 0 when it only finds lines that don't match xxxx
, and 1
if it finds a line that matches. The !
operator inverts this status, and the if
tests whether the inverted status is 0, executing the then
code if the inverted status is 0.
Note that [
is just a command that returns a suitable exit status which the if
tests. On many systems, you can find /bin/[
as an executable, maybe as a (symbolic?) link to /bin/test
— but modern shells invariably treat [
and test
as built-in commands. Note that [
checks that its last argument is ]
and objects if it isn't; test
does not.