13

Take the following shell script, for example:

#!/bin/bash
python do_this_first.py 
python do_this_second.py
python do_this_last.py

When I run the above, will the 3 python scripts run parallel? As I want 'do_this_second' to run only after 'do_this_first' has completed.

3 Answers 3

32

As it stands, they will be run one after another, regardless of whether they failed or not. They only have to exit at some point, then the next command is run. One after another.

If you want them to be executed only if the previous commands did not exit with an error, use:

python do_this_first.py && python do_this_second.py && python do_this_last.py

Here, the two ampersands work like a logical AND. The second script will only run when the first one has exited cleanly, and the third one only when the second one ran without errors. If there was any error, none of the following commands will run.


If you however want to run them in parallel, you could do this — but there are plenty of other options:

python do_this_first.py &
python do_this_second.py &
python do_this_last.py &
3

The bash is sequential. In the beginning do_this_first.py file will be interpreted. After python finishes executing it, the control is transferred to bash again. The bash in turn will execute python do_this_second.py and so on..
So essentially, do_this_first starts and finish, do_this_second starts and finish and then do_this_last starts and finish.

2

As slhck said, the following is one option.

python do_this_first.py && python do_this_second.py && python do_this_last.py

Or you could set -e, which will exit immediately, if a line returns an error code.

#!/bin/bash

# Exit immediately if a command exits with a non-zero status.
set -e

python do_this_first.py 
python do_this_second.py
python do_this_last.py

For me, this last one is more readable.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .