Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallelizing lines (commands, processes...) on a Linux shell script

I am managing a WiFi network with multiple repeaters (access points).
I have made a script that counts the number of connected users on each one. Example for AP 1 and 2:

luis@Fresoncio:~/Temporal/ClientesActivos$ ./ClientesActivos-AP-N.sh 1
3
luis@Fresoncio:~/Temporal/ClientesActivos$ ./ClientesActivos-AP-N.sh 2
10

But it is a bit slow. Example for AP 3:

luis@Fresoncio:~/Temporal/ClientesActivos$ time ./ClientesActivos-AP-N.sh 3
5
real    0m7.074s
user    0m0.040s
sys     0m0.040s

So, as long as I have more than 10 APs, I would like to parallelize all the readings. I have made another script that calls the individual requests in background. Something like:

AP-1=$(./ClientesActivos-AP-N.sh 1) &
AP-2=$(./ClientesActivos-AP-N.sh 2) &
AP-3=$(./ClientesActivos-AP-N.sh 3) &
... etc
sleep 20    # Wait 20 seconds for all readings to finish.
echo "$AP-1, $AP-2, $AP-3... etc"

But this does not seem to work. At least on shell tests:

luis@Fresoncio:~/Temporal/ClientesActivos$ echo $a

luis@Fresoncio:~/Temporal/ClientesActivos$ a=$(./ClientesActivos-AP-N.sh 4)
luis@Fresoncio:~/Temporal/ClientesActivos$ echo $a
6
luis@Fresoncio:~/Temporal/ClientesActivos$ unset a
luis@Fresoncio:~/Temporal/ClientesActivos$ echo $a

luis@Fresoncio:~/Temporal/ClientesActivos$ a=$(./ClientesActivos-AP-N.sh 4) &
[1] 13527
[A few minutes later...]
luis@Fresoncio:~/Temporal/ClientesActivos$ echo $a

[1]+  Done                    a=$(./ClientesActivos-AP-N.sh 4)

What am I doing wrong and what is the method to parallelize individual lines in a shell script? Is background processing the right method?

Further data:

  • My shell is Bash, but generic answers would be useful too.
like image 727
Sopalajo de Arrierez Avatar asked May 11 '26 06:05

Sopalajo de Arrierez


1 Answers

The easiest way would be to use GNU Parallel

Example:

parallel ./ClientesActivos-AP-N.sh ::: $(seq 1 5)
like image 68
OneOfOne Avatar answered May 12 '26 23:05

OneOfOne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!