8

I'd like to have a very simple condition that will only execute if the command fails.

In this example it's a conditional based on the SUCCESS of the command.

if command ; then
    echo "Command succeeded"
fi

I'd like the opposite - how can I do this? Is there a elagant way besides doing a comparison on $?

I do not want to use the || or operator - it does semantically convey (in my opinion) the desired functionality. In the case of command || echo "command failed".

Chris Stryczynski
  • 5,178
  • 5
  • 40
  • 80
  • Related: [What are the shell's control and redirection operators?](https://unix.stackexchange.com/a/159514/65304) – steeldriver Oct 09 '19 at 13:39
  • You may find examples in this thread useful: https://askubuntu.com/questions/512770/what-is-use-of-command-command
    `command -v "$1" >/dev/null 2>&1`
    – t7e Jun 25 '22 at 14:47

2 Answers2

22

Negate the command’s exit status:

if ! command ; then
    echo "Command failed"
fi
Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
3

An alternative to @StephenKitt's correct answer: use the : "no-op" command in the "then" block and the else block:

if command; then :; else
    echo "command failed"
fi

Full disclosure: I would not use this method myself.

glenn jackman
  • 84,176
  • 15
  • 116
  • 168