在循环 bash 中等待
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29853974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wait inside loop bash
提问by Preston Alexander
I have created a loop to read through a .txt
and execute another shell using each line as input.
我创建了一个循环来读取 a.txt
并使用每一行作为输入执行另一个 shell。
PROBLEM:I need the loop to execute the first two lines from the txt in parallel, wait for them to finish, then execute the next two lines in parallel.
问题:我需要循环并行执行 txt 中的前两行,等待它们完成,然后并行执行接下来的两行。
ATTEMPT AT SOLUTION:I thought of adding in a wait command, just not sure how to structure so it waits for every two lines, as opposed to each churn of the loop.
尝试解决方案:我想添加一个等待命令,只是不确定如何构建它,以便每两行等待一次,而不是循环的每次搅动。
My current loop:
我当前的循环:
cat input.txt | while read line; do
export step=${line//\"/}
export step=ExecuteModel_${step//,/_}
export pov=$line
$owsdirectory"/hpm_ws_client.sh" processCalcScriptOptions "$appName" "$pov" "$layers" "$stages" "" "$stages" "$stages" FALSE > "$appLogFolder""/"$step"_ProcessID.log"
/app/dev2/batch/hpcm/shellexe/rate_tool2/model_automation/check_process_status.sh "$appLogFolder" "$step" > "$appLogFolder""/""$step""_Monitor.log"
Input txt:
输入txt:
SEQ010,FY15
SEQ010,FY16
SEQ020,FY15
SEQ020,FY16
SEQ030,FY15
SEQ030,FY16
SEQ030,FY15
SEQ030,FY16
SEQ040,FY15
SEQ040,FY16
SEQ050,FY15
SEQ050,FY16
回答by that other guy
Normally you'd use sem
, xargs
or parallel
to parallelize a loop, but all these tools optimize throughput by always having 2 (or N) jobs running in parallel, and starting new ones as old ones finish.
通常您会使用sem
,xargs
或parallel
来并行化循环,但所有这些工具都通过始终并行运行 2 个(或 N 个)作业并在旧作业完成时启动新作业来优化吞吐量。
To instead run pairs of jobs and wait for both to finish before considering starting more, you can just run them in the background and keep a counter to wait
every N iterations:
要运行成对的作业并在考虑启动更多作业之前等待它们完成,您可以在后台运行它们并保持wait
每 N 次迭代的计数器:
printf "%s\n" {1..10} | while IFS= read -r line
do
echo "Starting command"
sleep 2 &
if (( ++i % 2 == 0 ))
then
echo "Waiting..."
wait
fi
done
Output:
输出:
Starting command
Starting command
Waiting...
Starting command
Starting command
Waiting...