I'm trying to comprehend what are all the possible constructs you can pass to if
in bash.
In the GNU reference:
The syntax of the if statement is:
if test-commands; then
consequent-commands;
[elif more-test-commands; then
more-consequents;]
[else alternate-consequents;]
fi
The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed...
So I understand that test-commands
may be anything that returns a status. So first I thought that this must be one of the followings:
- the test built-in (i.e. [ ] )
- The [[ ]] syntax
- some command (may be any executable)
And as I knew the test command, it has a !
operator (among others) that can inverse the return of the conditional statement you put in it, as such:
if [ ! -z "non-empty" ]; then echo "ok"; fi
Until then I was happy thinking I know bash. But then I found that I can do:
if ! [ -z "non-empty" ]; echo "Ok!"; fi
That breaked my heart - I thought that the !
thing belongs to the test command (also to the [[]] syntax) - but what is it outside of it? And why does if
takes it?
What construct exactly is !
? And are there other things acceptable?