7

I came across a if/then statement like this:

if ! foo ; then
        echo "blah" 
        exit 1
fi

What specifically does if ! mean? "If the result of foo is not true?" "If the exit code of foo is not 0"?

  • 1
    if ! is the short form of unless :-O – Jens Oct 18 '14 at 19:02
  • its like if != – jgr208 Oct 19 '14 at 2:40
  • @Jens Booleans are much easier to understand if you see it as ! foo (regardless of whether it's in an if or not). – IQAndreas Oct 19 '14 at 7:47
  • @IQAndreas I believe that's mostly personal preference. At least perl has a built-in unless keyword and some people like it. – Jens Oct 19 '14 at 10:22
16

! inverts the meaning of the exit status of the command -- it's part of POSIX shell syntax, it's not part of if. From the POSIX spec:

If the reserved word ! does not precede the pipeline, the exit status shall be the exit status of the last command specified in the pipeline. Otherwise, the exit status shall be the logical NOT of the exit status of the last command. That is, if the last command returns zero, the exit status shall be 1; if the last command returns greater than zero, the exit status shall be zero.

11

It is a boolean operator that equates to the logical not.

See man bash:

! expression
    True if expression is false.

In your example, if not foo, echo blah.

6

Just to add to the other answers, the code uses ! to avoid writing the code like this:

if foo ; then
    # everything that used to follow "fi" in the previous version
else
    echo "blah" 
    exit 1
fi

That only works if there is something after the fi in the script, since an empty if clause isn't legal. (A comment doesn't count.)

Writing it this way costs you an indent level, which the hard-core structured programming folks will tell you is a cost worth paying. This school of software development says that an exit in the middle of a program is scarcely better than goto end, and since goto is an unmitigated evil, the extra nesting level is an improvement.

One competing school says, "Yeah, indents are great until you've pushed all the code off the right hand side of the screen."

Then you get those who think both camps are a little bonkers, and simply observe that it's better to avoid negative logic where possible, and that the normal case should be the first one, with exceptions off at the end of the program.

Pick your kool-aid and drink it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.