Is there a standard command that always exits with a failure?

25,667

You can use false (/bin/false, /usr/bin/false, or shell builtin):

$ false || echo It failed.
It failed.
$

You can also use exit 1 from a subshell:

$ (exit 1) || echo Gosh, it failed too.
Gosh, it failed too.
$
Share:
25,667

Related videos on Youtube

ljubomir
Author by

ljubomir

Updated on September 18, 2022

Comments

  • ljubomir
    ljubomir almost 2 years

    I want to test my script with a command that fails. I could use an existing command with bad arguments. I could also write a simple script that immediately exits with a failure. Both of these are easy to do and work for me, but if there is a standard command for this purpose, I'd like to use that instead.

    • Kusalananda
      Kusalananda almost 5 years
      false, but also any non-existent command.
  • mtraceur
    mtraceur over 7 years
    Additionally, you can portably call exit with any number in the range 1-255, inclusive. (Most shells will apply a modulo 255 operation on any other numbers given to exit, so in practice you can get away with other numbers though they're just coerced into the aforementioned range. But some shells will do other things, for example exit with a syntax error (still a failure status though) if called with a negative value. Unix-like systems only support exit codes within the range 0-255 inclusive, which is why you can't rely on well-defined behavior for other values given to exit in all shells.)
  • mtraceur
    mtraceur over 7 years
    And as a bit of trivia, unless you need portability to really old/obscure shells, you can also do ! : (or any other command that normally returns success). ! says to negate the exit status of the command that follows. : is just the noop builtin command which always exits with success. (Just make sure to leave a space after the ! and before the command being negated, otherwise it'll try to parse it as one command starting with a ! character - or in the case of shells like bash in interactive mode, it parses it as one of those special history modifiers.)