0

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?

1
  • 1
    Your example lanunches them in a sequence. So, every proram will run after the previous finished. (unless the programs forks itself). For the parallel execution you need send them to the background (using &) or by using gnu parallel or xargs -P and such... Commented Mar 8, 2017 at 17:32

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.