Pleasant94
Pleasant94

Reputation: 501

Bash script - How to know a program has terminated

I have created a script that compiles and then executes 4 .c programs.

Now, my script is the following:

#!/bin/sh

echo "Compiling first program. . ."
gcc -o first first.c
echo "File compiled."
echo

echo "Compiling second program. . ."
gcc -o second second.c
echo "File compiled."
echo

echo "Compiling third program. . ."
gcc -o third third.c
echo "File compiled."
echo

echo "Compiling fourth program. . ."
gcc -o fourth fourth.c
echo "File compiled."
echo

./first
./second
./third
./fourth

Every executable file needs to run alone. The question is: launching the execs in that way, will they be executed simultaneously? How do I know when a program has terminated before launching the following one?

Upvotes: 0

Views: 420

Answers (1)

ruakh
ruakh

Reputation: 183361

Each command in a Bash script will complete before the next one starts, unless you specifically use a feature that does otherwise, such as &:

foo bar &                # starts `foo bar` to run "in the background"
                         # while the script proceeds

or |:

foo | bar                # runs `foo` and `bar` in parallel, with output
                         # from `foo` fed as input into `bar. (This is
                         # called a "pipeline", and is a very important
                         # concept for using Bash and similar shells.)

That said, this doesn't mean that the command completed successfully. In your case, some of your gcc commands might fail, and yet the other programs would still be run. That's probably not what you want. I'd suggest adding something like || { echo "Command failed." >&2 ; exit 1 ; } to each of your commands, so that if they fail (meaning: if they return an exit status other than 0), your script will print an error-message and exit. For example:

gcc -o first first.c || { echo "Compilation failed." >&2 ; exit 1 ; }

and:

./second || { echo "Second program failed." >&2 ; exit 1 ; }

(You can also put this sort of logic in a "function", but that's probably a lesson for another day!)

I recommend reading through a Bash tutorial, by the way, and/or the Bash Reference Manual, to get a better handle on shell scripting.

Upvotes: 2

Related Questions