簡體   English   中英

如何捕獲和前綴處理 output 在 bash 腳本中啟動?

[英]How to capture and prefix to process output started within a bash script?

我正在編寫一個小的 bash 腳本,我正在編譯 2 個程序,然后在 bash 腳本的后台執行它們。 這 2 個程序執行 output 一些通用文本。 但是我需要為這些輸出添加前綴,例如PROGRAM1: xxxxx 我如何做到這一點? 我在這里找到了幾個答案,但它們並不完全適用於這種情況。

這是代碼:

#!/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
gcc -O3 -std=c11 two.c -o two

./two &
sleep 0.01
TWO_PID=$(pgrep two)

./one $TWO_PID

#"Prefix output statements here"
#add code here

#Cleanup
rm -f one two

你可以這樣做

#! /bin/bash

# ...

label() {
    while read -r l; do
        echo "$1: $l"
    done
}

./two | label "two" &
two_pid=$(pgrep two)
./one $two_pid | label "one"

您不需要 sleep 並且要小心,因為pgrep可以匹配多個進程。

另外,您應該使用make而不是編譯和刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM