Bash (single line): Execute 2nd command if first succeeds, execute 3rd if it doesn’t

bashcommand line

I want to execute two commands one after another via SSH. I don't have an interactive shell. The second command should only execute if the first one succeeds, but the line is inside a script, so I'd like some user-friendly feedback if the second command fails to execute this way. After that, the rest of the script should continue executing, so exit, etc. is not an option here.

I know I can use the boolean operator &&, e.g. foo && bar to prevent bar from executing if foo fails, and bar || baz to execute baz only on bar's failure. However I am a little confused as to how these work in conjunction with each other.

To sum it up:

(Executed via SSH without an interactive shell)

  1. Execute foo
  2. Execute bar ONLY if foo succeeds
  3. Execute baz ONLY if foo fails and prevents the execution of bar

ssh user@host "foo && bar || baz"

Is this a correct way to do what I just described?

Best Answer

Using your example foo && bar || baz will execute baz if bar or foo fails. Based on your description, this not what you want. You can accomplish your goal using an if statement:

if foo; then
    bar
else
    baz
fi

Or if you want it on one line:

if foo; then bar; else baz; fi
Related Question