You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash中如何同时使用&后台运行符与&&命令串联符?

正确实现方法

你原来的写法报错的核心原因是:Bash 中&和&&都属于命令终止符,不能直接连续使用。&的作用是将前方命令提交到后台执行,执行后会立即返回当前 Shell,不需要加&&就能直接执行后续命令。

最简写法(分行)

my-program &
another-program-that-monitors-the-first $!

$!是Shell内置变量,会自动保存最后一个被放入后台的进程的PID,后台启动my-program后立刻调用$!就能拿到正确的进程ID,完全符合你的需求。

单行写法

如果需要写在同一行,用分号分隔两条命令即可:

my-program & another-program-that-monitors-the-first $!

带启动校验的写法

如果需要先确认my-program确实启动成功再运行监控,可以加一层判断:

my-program &
prog_pid=$!
# 校验进程是否存在
if ps -p "$prog_pid" > /dev/null 2>&1; then
  another-program-that-monitors-the-first "$prog_pid"
else
  echo "my-program 启动失败"
  exit 1
fi

整体后台运行写法

如果你需要把「启动程序+运行监控」这一整套逻辑都放到后台执行,用命令组包裹后再加&即可:

{
  my-program &
  another-program-that-monitors-the-first $!
} &

内容的提问来源于stack exchange,提问作者David Callanan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 06:51:00