Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

linux - How to run a command in a bash script from a loop with different arguments simultaneously in the background, while formatting the output

The following snippet will run within the script, but it takes a long time for each loop.

#!/bin/bash
….
some_command $A $B $C | awk ‘{print$1}’ | while read -r var1; do
    printf "
$var1 
"
    printf "
"
    other_command $var1
    printf "
"
done
….

I tried running this, but the printf statements will run before the other_command, which is used to make the output a little more readable.

#!/bin/bash
….
some_command $A $B $C | awk ‘{print$1}’ | while read -r var1; do
    printf "
$var1 
"
    printf "
"|
    other_command $var1 &
    printf "
"
done
wait 
….

If I run just other_command with the & in loop I get the desired result but it it not very readable.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The idea is to move the long running command into a function, and call this function multiple times as child processes. This way they can run in parallel. Inside the function, the output from the command is first written into a local variable, and only printed in one go after the command is done.

#!/bin/bash

function do_something () {
  local OUTPUT="$(other_command "$var1")"
  printf "
%s

%s
" "$1" "$OUTPUT";
}

some_command "$A" "$B" "$C" | while read -r "var1" "_";
do
  do_something "$var1" &
done

wait

Please note that the order of the output will (probably) be different on every call, which is inherent to parallel execution.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...