Reputation: 3028
I have a small bash
test script like this:
$ cat test
#!/bin/bash
if ! grep --silent "$1" "$3"; then echo "$1 not matched."; fi; exit 1;
if ! grep --silent "$2" "$3"; then echo "$2 not matched."; fi; exit 1;
and a test file like this:
$ cat foobar
FOO
BAR
Now I do the following:
$ ./test FOO BAR foobar
$ ./test FOOH BAR foobar
FOOH not matched.
$ ./test FOO BARG foobar
$
In my mind the last run, ./test FOO BARG foobar
should produce the output BARG not matched.
and the script stop executing. What's the reason this does not work as I expect it to? Is there a better way of achieving the same logic?
Edit:
Also, if I comment out the second statement, like this:
$ cat test
#!/bin/bash
#if ! grep --silent "$1" "$3"; then echo "$1 not matched."; fi; exit 1;
if ! grep --silent "$2" "$3"; then echo "$2 not matched."; fi; exit 1;
The second if statement is executed:
$ ./test FOO BARG
$ BARG not matched.
So it seems that only the first of the consecutive if statements are executed. This also happens if I extend the script to have three similar if statements.
Upvotes: 0
Views: 57
Reputation: 4628
Your code looks like this with bit better formatting:
#!/bin/bash
if ! grep --silent "$1" "$3"; then
echo "$1 not matched.";
fi;
exit 1;
if ! grep --silent "$2" "$3"; then
echo "$2 not matched.";
fi;
exit 1;
Probably you wanted to have the exit statements within the ifs:
#!/bin/bash
if ! grep --silent "$1" "$3"; then
echo "$1 not matched.";
exit 1;
fi;
if ! grep --silent "$2" "$3"; then
echo "$2 not matched.";
exit 1;
fi;
Upvotes: 3