Search code examples
bashconditional-statementsexitstatus

What's the exit status of a failed condition?


[ $var -eq $val ]

What will be the value of $? after the above condition/test if it fails? Can I assume that it will always be 1?

Edit: After reading answers I realized my question wasn't precise. I meant "will it be always 1 if no error occurs?".


Solution

  • Yes, at least as long as an error doesn't occur (so technically "no" in the general case, I guess?). See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html#tag_20_128_14:

    The following exit values shall be returned:

    • 0

      expression evaluated to true.

    • 1

      expression evaluated to false or expression was missing.

    • >1

      An error occurred.

    Or https://www.gnu.org/software/bash/manual/bashref.html#Bourne-Shell-Builtins:

    Evaluate a conditional expression expr and return a status of 0 (true) or 1 (false).