如何执行 Bash 命令并在失败时执行两条语句?

Ale*_*lex 7 shell bash control-flow

当且仅当测试返回错误时,我想执行 Bash 命令,然后执行两个操作。我更愿意在 Bash 中以单行方式解决此任务。

这是我尝试过的两种形式:

ssh user@1.2.3.4 "ls /home/somefile" || echo "File does not exist" && exit 1
ssh user@1.2.3.4 "ls /home/somefile" || echo "File does not exist"; exit 1
Run Code Online (Sandbox Code Playgroud)

含义如下:我想测试远程机器上文件的存在(或其他任何东西,只是一个例子),在第一个命令返回错误的情况下,然后 - 只有这样 - 以下两个命令(echo/ exit) 应该被执行。上面的示例exit 1独立于ssh命令的返回值执行语句。

如何重写这一行,以便仅在第一个 ( ) 命令失败时才执行echoexit命令ssh

Mar*_*ich 19

ssh user@1.2.3.4 "ls /home/somefile" || { echo "File does not exist"; exit 1; }
Run Code Online (Sandbox Code Playgroud)

这称为复合命令。来自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.
Run Code Online (Sandbox Code Playgroud)

()语法在您的情况下可能不起作用,因为命令将在子外壳中执行,然后exit将关闭子外壳。

编辑:解释括号()和花括号之间的区别{}

括号导致在子shell 中执行包含的命令。这意味着会产生另一个 shell 进程来评估命令,并且exitin OP 的问题会杀死这个子 shell。

相反,大括号会导致在当前 shell 中评估命令。现在exit杀死当前的 shell,例如,如果您使用这一行 shell 脚本,这将是更可取的。