Shell – What does “if !” mean

shell

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"?

Best Answer

! 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.