9

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

2 Answers2

24

Negate the command’s exit status:

if ! command ; then
    echo "Command failed"
fi
Stephen Kitt
  • 434,908
4

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
  • 85,964