Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use parallel execution in a shell script?

I have a C shell script that does something like this:

#!/bin/csh
gcc example.c -o ex
gcc combine.c -o combine
ex file1 r1     <-- 1
ex file2 r2     <-- 2
ex file3 r3     <-- 3
#... many more like the above
combine r1 r2 r3 final
\rm r1 r2 r3

Is there some way I can make lines 1, 2 and 3 run in parallel instead of one after the another?

like image 328
Lazer Avatar asked May 07 '10 19:05

Lazer


People also ask

How do I run a parallel command in Unix?

By default, the command is run sequentially at each computer, but you can specify to run the commands in parallel using background rshells by prefixing the command with certain prefix sequences. If the rshell is run in the background, then each command puts the output in a buffer file at its remote computer.

What is && and || in shell script?

The operators "&&" and "||" shall have equal precedence and shall be evaluated with left associativity. For example, both of the following commands write solely bar to standard output: $ false && echo foo || echo bar $ true || echo foo && echo bar.


2 Answers

Convert this into a Makefile with proper dependencies. Then you can use make -j to have Make run everything possible in parallel.

Note that all the indents in a Makefile must be TABs. TAB shows Make where the commands to run are.

Also note that this Makefile is now using GNU Make extensions (the wildcard and subst functions).

It might look like this:

export PATH := .:${PATH}

FILES=$(wildcard file*)
RFILES=$(subst file,r,${FILES})

final: combine ${RFILES}
    combine ${RFILES} final
    rm ${RFILES}

ex: example.c

combine: combine.c

r%: file% ex
    ex $< $@
like image 65
Zan Lynx Avatar answered Oct 24 '22 06:10

Zan Lynx


In bash I would do;

ex file1 r1  &
ex file2 r2  &
ex file3 r3  &
wait
... continue with script...

and spawn them out to run in parallel. You can check out this SO thread for another example.

like image 32
AlG Avatar answered Oct 24 '22 06:10

AlG