1

.

I have a simple bash script where i run 3 at the same time and when they are done they start with the next 3 like this:

command1 &
command2 &
command3 &
wait
command4 &
command5 &
command6 &
exit

But how can i do so i always run 3 of these at the same time and not wait for the other three? lets say command1 and command2 finished but command3 still runnin, then i want command4 and command5 to start so there is always 3 commands running.

Thanks

  • With current GNU xargs: Put your commands in a text file. Each command in a separate line and then execute the following: `xargs -n 1 -P 3 -I {} bash -c {} < file_with_commands` – Cyrus Dec 31 '17 at 22:44
  • I tried using this: max_jobs=3 declare -A cur_jobs=( ) # build an associative array w/ PIDs of jobs we started for ((i=0; i<6; i++)); do if (( ${#cur_jobs[@]} >= max_jobs )); then wait -n # wait for at least one job to exit # ...and then remove any jobs that aren't running from the table for pid in "${!cur_jobs[@]}"; do kill -0 "$pid" 2>/dev/null && unset cur_jobs[$pid] done fi ./j"$i" & cur_jobs[$!]=1done wait But how can i specify the dir? command1 and command2 for example have different locations –  Jan 01 '18 at 10:02

1 Answers1

0

bash 4.3 introduced a -n option to wait, which lets you wait for the next job to complete.

command1 &
command2 &
command3 &
wait -n
command4 &
wait -n
command5 &
wait -n
command6 &
exit
chepner
  • 497,756
  • 71
  • 530
  • 681