1 |
On Mon, 14 Mar 2022 11:13:13 +0100 |
2 |
"J. Roeleveld" <joost@××××××××.org> wrote: |
3 |
|
4 |
> Hi, |
5 |
> |
6 |
> I often put multiple commands into a single file/script to be run in sequence. |
7 |
> (each line can be executed individually, there is no dependency) |
8 |
> |
9 |
> Is there a tool/method to execute multiple lines/commands simultaneously? Like |
10 |
> having 3 or 4 run together and when 1 is finished, it will grab the next one in |
11 |
> the list? |
12 |
> |
13 |
> I would prefer this over simply splitting the file as the different lines/ |
14 |
> commands will not take the same amount of time. |
15 |
> |
16 |
> Thanks, |
17 |
> |
18 |
> Joost |
19 |
> |
20 |
> |
21 |
> |
22 |
|
23 |
At the end there's a very rudimentary bash script to do this. I did not |
24 |
do much debugging (probably it fails already if max_jobs>#list_of_jobs). |
25 |
Anyway it's just making use of sending jobs to the background and |
26 |
"communicating" through a FIFO pipe (which you might want to delete at |
27 |
the end). |
28 |
#!/bin/bash |
29 |
|
30 |
list_of_jobs=("sleep 3" "sleep 5" "sleep 1" "sleep 10" "sleep 4") |
31 |
max_jobs=2 |
32 |
my_fifo=/tmp/my_job_fifo |
33 |
write_to_fifo="yes" |
34 |
|
35 |
function run_job () { |
36 |
eval "$@" |
37 |
if [[ $write_to_fifo == "yes" ]]; then |
38 |
echo "Writing to fifo ($@)" |
39 |
echo 1 > ${my_fifo} |
40 |
fi |
41 |
echo Finished job "$@" |
42 |
} |
43 |
|
44 |
function read_and_start_job() { |
45 |
next_job_idx=0 |
46 |
while [[ ${#list_of_jobs[@]} -gt $next_job_idx ]]; do |
47 |
while IFS= read -r line ; do |
48 |
echo "next_job_idx=${next_job_idx} total=${#list_of_jobs[@]}" |
49 |
if [[ $next_job_idx -lt ${#list_of_jobs[@]} ]] ; then |
50 |
job="${list_of_jobs[${next_job_idx}]}" |
51 |
echo "Executing: ${job}" |
52 |
run_job ${job} & |
53 |
let next_job_idx++ |
54 |
else |
55 |
echo "Set write_to_fifo=no" |
56 |
write_to_fifo="no" |
57 |
fi |
58 |
done < ${my_fifo} |
59 |
done |
60 |
write_to_fifo="no" |
61 |
wait |
62 |
} |
63 |
|
64 |
rm -Rf ${my_fifo} |
65 |
mkfifo ${my_fifo} |
66 |
read_and_start_job & |
67 |
while [[ ${max_jobs} -gt 0 ]] ; do |
68 |
let max_jobs-- |
69 |
echo 1 > ${my_fifo} |
70 |
done |
71 |
wait |