ssh user@1.2.3.4 "ls /home/somefile" || { echo "File does not exist"; exit 1; }
This is called a compound command. From man bash
:
Compound Commands
A compound command is one of the following:
(list) list is executed in a subshell environment (see COMMAND EXECU‐
TION ENVIRONMENT below). Variable assignments and builtin com‐
mands that affect the shell's environment do not remain in
effect after the command completes. The return status is the
exit status of list.
{ list; }
list is simply executed in the current shell environment. list
must be terminated with a newline or semicolon. This is known
as a group command. The return status is the exit status of
list. Note that unlike the metacharacters ( and ), { and } are
reserved words and must occur where a reserved word is permitted
to be recognized. Since they do not cause a word break, they
must be separated from list by whitespace or another shell
metacharacter.
The ()
syntax probably wouldn't work in your situation because the commands would be executed in a subshell, and then the exit
would just close the subshell.
EDIT: to explain the difference between the parentheses ()
and the curly braces {}
:
The parentheses cause the contained commands to be executed in a subshell. That means that another shell process is spawned which evaluates the commands, and the exit
in OP's question would kill this subshell.
The curly braces instead cause the commands to be evaluated in the current shell. Now the exit
kills the current shell, which would be for example preferable if you use this line a shell script.
What you're searching is something like this:
[ "$USER" = "x" ] || { echo "Time to bail"; exit 1; }
The { list; }
statement executes the commands in the given list in the current shell context. No subshell is created, unlike in the ( list )
notation. An exit
call between parentheses will exit that subshell and not the parent shell itself.
The examples in your question with the if-statement on one line or multiple lines are syntactically correct. I cannot reproduce that behavior. It doesn't matter how many lines there arre; the if-statement never starts a subshell in its body.
BTW: I added double quotes to the variable in the condition, because when the variable $USER
is empty, the construct would expand to [ = "x" ]
which is not valid. With double quotes it expands to [ "" = "x" ]
.
Best Answer
Here, also using
zsh
, I haveAnd similarly
Are you sure that you are seeing
hai
andbye
on the same line with exactly the commands you have provided here?In direct answer to your question, an exit status of zero is success, so the second statement is executed. (This allows different non-zero exit status values to indicate different errors.)