Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script, for loop, does loop wait for execution of the command to iterate

I have a shell script with a for loop. Does loop wait for execution of the command in its body before iterating?

Thanks in Advance

Here is my code. Will the commands execute sequentially or parallel?

for m in "${mode[@]}" 
    do 
        cmd="exec $perlExecutablePath $perlScriptFilePath --owner $j -rel $i -m $m"
        $cmd
        eval "$cmd"
    done
like image 872
Ankit Kumar Singhal Avatar asked Jun 05 '15 09:06

Ankit Kumar Singhal


1 Answers

Assuming that you haven't background-ed the command, then yes.

For example:

for i in {1..10}; do cmd; done

waits for cmd to complete before continuing the loop, whereas:

for i in {1..10}; do cmd &; done

doesn't.

If you want to run your commands in parallel, I would suggest changing your loop to something like this:

for m in "${mode[@]}" 
do 
    "$perlExecutablePath" "$perlScriptFilePath" --owner "$j" -rel "$i" -m "$m" &
done

This runs each command in the background, so it doesn't wait for one command to finish before the next one starts.

An alternative would be to look at GNU Parallel, which is designed for this purpose.

like image 87
Tom Fenech Avatar answered Sep 30 '22 03:09

Tom Fenech