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

如何在Bash脚本中捕获进程输出并添加自定义前缀?

给后台运行的Bash程序输出添加前缀的解决方案

修改后的脚本(基础版本)

#!/bin/bash
echo "This program compiles 2 programs, executes them (executes the 2nd one first, then sleeps for 0.01 second which then executes program 1), then observes the outputs"

# 编译程序,失败则直接退出
gcc -O3 -std=c11 one.c -o one || exit 1
gcc -O3 -std=c11 two.c -o two || exit 1

# 后台运行two,给所有输出(含错误)添加PROGRAM2前缀
./two 2>&1 | sed 's/^/PROGRAM2: /' &
# 获取two的PID,$!是刚启动的后台进程PID,比pgrep更可靠
TWO_PID=$!

sleep 0.01

# 前台运行one,给所有输出(含错误)添加PROGRAM1前缀
./one "$TWO_PID" 2>&1 | sed 's/^/PROGRAM1: /'

# 等待后台的two进程执行完毕
wait "$TWO_PID"

# 清理生成的可执行文件
rm -f one two

关键改动说明

  • 可靠获取后台进程PID:用$!替代pgrep two,直接获取刚启动的./two进程ID,避免系统中存在其他同名进程导致的PID错误。
  • 输出前缀处理:通过2>&1将程序的标准错误(stderr)合并到标准输出(stdout),再通过管道传给sed命令,给每一行输出开头添加指定前缀,确保正常输出和错误信息都能被标记。
  • 编译失败防护:在编译命令后追加|| exit 1,一旦编译失败立即退出脚本,避免后续执行无效的可执行文件。
  • 等待后台进程结束:添加wait "$TWO_PID"确保two进程完全执行后再清理文件,防止提前删除可执行文件导致进程异常。

双后台运行版本(可选)

如果需要两个程序都在后台运行,同时查看带前缀的输出,可以使用以下脚本:

#!/bin/bash
echo "This program compiles 2 programs, executes them in background, then observes the prefixed outputs"

gcc -O3 -std=c11 one.c -o one || exit 1
gcc -O3 -std=c11 two.c -o two || exit 1

# 后台运行two并添加前缀
./two 2>&1 | sed 's/^/PROGRAM2: /' &
TWO_PID=$!

sleep 0.01

# 后台运行one并添加前缀
./one "$TWO_PID" 2>&1 | sed 's/^/PROGRAM1: /' &
ONE_PID=$!

# 等待两个后台进程全部完成
wait "$ONE_PID" "$TWO_PID"

rm -f one two

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:35:27