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)
- Execute
foo
- Execute
bar
ONLY iffoo
succeeds - Execute
baz
ONLY iffoo
fails and prevents the execution ofbar
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 executebaz
ifbar
orfoo
fails. Based on your description, this not what you want. You can accomplish your goal using anif
statement:Or if you want it on one line: