0

I want to run a command with different arguments in multi-threading form,

What I tried is:

#!/bin/bash

ARG1=$1
ARG2=$2
ARG3=$3

for ...  #counter is i
do
 main command with ARG1 ARG2 ARG3  & a[i]=$!
done
wait `echo  ${a[@]}`

I used & a[i]=$! in for loop and wait $(echo ${a[@]}) after for loop. I want my bash to wail till all threads finish then echo their pid for me...

But when I run my script after some time it waits.

Thank you

MLSC
  • 5,872
  • 8
  • 55
  • 89
  • _But when I run my script after some time it waits._ -- It's not quite clear what this means. – devnull May 07 '14 at 07:38
  • yes I mean it doesn't finish running script...just waits, in this way:`Nmap done: 1 IP address (1 host up) scanned in 0.43 seconds` doesn't finish – MLSC May 07 '14 at 07:44
  • Do you even need to supply an argument to `wait`. Without any argument, `wait` would wait for all child processes. – devnull May 07 '14 at 07:45
  • I just want to save pid in arg and wait till all of pid finish, when they are all finished echo their pids – MLSC May 07 '14 at 07:52
  • dose it work if you use another command? do any jobs with your original command really finish? can you show the command you are using? – mofoe May 07 '14 at 07:56
  • Thank you guys..I found ... `& a[i]=$!` should be `& a[$i]=$!` – MLSC May 07 '14 at 08:16

1 Answers1

0

I think you want this:

#!/bin/bash
for i in 0 1 2
do
   sleep 3 & a[$i]=$!
done
wait
echo ${a[@]}

You are missing the $ on the array index $i in your script. Also, you don't need to say which PIDs you are wating for if you are waiting for all of them. And you also said you wanted to see the list of PIDs at the end.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432