并行运行脚本时 Bash 脚本不休眠

并行运行脚本时 Bash 脚本不休眠

我有几个需要并行运行的 bash 脚本。然而,它们非常消耗内存,所以我想将它们每一个错开 30 秒,但仍然并行运行。例如:

hourr=($(seq 0 1 23))

for q in "${hourr[@]}";
do;
echo $q; sleep 10;
done

这会等待 10 秒,然后按顺序输出一个数字,从 0 到 23。但是,当我尝试使用脚本执行此操作时:

hourr=($(seq 0 1 23))
input1="20160101"; 
input2="10"; #(Note: These are inputs to each of the scripts I want to run)
scriptdir="/path/to/somewhere"
for q in "${hourr[@]}"
do
if [ "${#q}" == "1" ]
then
hh=0${q}
else
hh=${q}
fi
echo $hh
( bash $scriptdir/Hour$hh.csh $input1 $input2 ; sleep 30 ) &
done
wait
echo "All done!"

但是,当执行主脚本时,所有 Hour 脚本都会立即运行(正确且并行),并且不会等待我指定的 30 秒一个接一个地运行。有什么想法吗?

答案1

如果你这样做怎么办?

#/bin/bash

input1='20160101'
input2='10' #(Note: These are inputs to each of the scripts I want to run)
scriptdir='/path/to/somewhere'
for q in {00..23}
do
    hh="${q}"
    echo "$hh"
    ( bash "$scriptdir/Hour$hh.csh" "$input1" "$input2" ) &
    sleep 30
done
wait
echo "All done!"

正如评论中所指出的,这&会导致您的脚本sleep也在后台执行,因此您的脚本在进入循环的下一次迭代之前不会等待它完成。你的hourr数组也是不必要的

相关内容