如何在一个命令行中运行多个命令?

我遇到了头痛的问题。

我想在后台执行多个命令,所以我想在bash中逐个启动它们。 在后台的linux shell中启动一个命令很容易,就像这样:

myCommand & 

启动多个命令也很容易,就像这样:

 myCommand1 && myCommand2 

要么

 myCommand1 ; myCommand2 

但是如果我想在后台运行多个命令,我尝试了以下命令格式,但是失败了:

 myCommand1 & && myCommand2 & 

要么

 myCommand1 & ; myCommand2 & 

两种格式都失败了 如何在一个命令行中运行多个命令?

使用 ()。

如果要按顺序运行它们:

 (myCommand1; myCommand2) & 

要么

 (myCommand1 &) && (myCommand2 &) 

如果您希望它们并行运行:

 myCommand1 & myCommand2 & 

在bash中你也可以使用它({和;后面的空格是强制的):

 { myCommand1 && myCommand2; } & 

我想你想要这个:

 myCommand1 & myCommand2 & 

这将启动myCommand1并将其发送到后台,因为它后面跟着&符号,然后立即启动myCommand2并将其发送到后台,从而再次释放shell。

清单

为了更好地理解,您可以在此处按命令替换管道

列表是由一个运算符分隔的一个或多个管道的序列;&&|| ,并可选择以其中一个终止; ,或

如果命令由控制操作符终止,则shell在子shell中在后台执行命令。 shell不等待命令完成,返回状态为0.命令由a分隔; 按顺序执行; shell等待每个命令依次终止。 返回状态是最后执行的命令的退出状态。

AND和OR列表是由&&||分隔的一个或多个管道的序列 分别控制运营商。
资料来源: man bash

让我们把它分解为例子。 您可以通过组合命令并使用以下方法之一来分隔它们来构建列表: ; & && ||

 command1 ; command2 # runs sequentially command1 && command2 # runs sequentially, runs command2 only if command1 succeeds command1 || command2 # runs sequentially, runs command2 only if command1 fails command1 & command2 # runs simultaneously 

您可以使用以下方法之一终止列表: ; & ; &
通常按Enter键执行命令或列表,等于 。 分号; 服务于同样的目的,特别是在脚本中。 然而,Ampersand会在后台的子shell中启动命令,立即释放shell。

您可以使用round ()或花括号{}来进一步分组列表,不同之处在于圆括号产生子shell而curl则不产生。 卷括号在第一个之后需要一个空格,在结束括号之前需要分号或换行符。 例如:

 # if c1 succeeds start a shell in the background # and run c2 and c3 sequentially inside it c1 && ( c2 ; c3 ) & # run c1 and if it succeeds c2 sequentially as a group command # if c1 or c2 fail run c3 in the background { c1 && c2 ;} || c3 & 

如果你不确定使用truefalse来测试结构是否按预期工作,这可能会变得非常复杂:

 $ { true && true ;} || echo 2 $ { true && false ;} || echo 2 2 

工作控制

jobs命令显示当前shell中正在运行或最近已完成的后台作业的列表。 有许多用于作业控制的键盘快捷键和命令:

  • Ctrl + Z键入暂停字符,该字符导致当前在前台运行的进程停止,它不会终止,但仍保留在jobs列表中
  • Ctrl + Y键入延迟挂起字符,该字符导致当前在前台运行的进程在尝试从终端读取输入时停止
  • fg = %将进程带入前台,必要时启动它,您可以按如下方式指定进程:

      % # last process in the jobs list %1 # 1st process in the jobs list %abc # process beginning with the string “abc” %?abc # process containing the string “abc” anywhere 
  • bg = %&将进程带入后台,必要时启动它:

      %& # last process in the jobs list %1& # 1st process in the jobs list %abc& # process beginning with the string “abc” %?abc& # process containing the string “abc” anywhere 
  • wait后台进程完成并返回其终止状态:

      wait %1 # 1st process in the jobs list 

    想象一下,你开始了一个漫长的过程( jobs显示它的数字3),然后意识到你希望计算机在完成时被暂停,如果进程没有成功则echo一条消息:

      wait %3 || echo failed ; systemctl suspend