tod
tod

Reputation: 1575

How to wait until everything started by a shell script ends?

I am using nested shell scripts.

My question is a bit similar to the ones asked here and here. But not exactly the same.

I have tried to get the solution from these but unsuccessful.

In my OuterMostShellScript.sh, I do something like this:

some commands
./runThisScriptX.sh
other commands
end of script.

runThisScriptX.sh contains a loop running some processes in the background by using & operator.

I want each process started by the ./runThisScriptX.sh command finish before the control moves to the, which i say other commands line in the above code.

how to achieve this?

EDIT: I also did like this:

some commands
./runThisScriptX.sh
wait
other commands
end of script.

but it did not work.

Upvotes: 0

Views: 2427

Answers (4)

chepner
chepner

Reputation: 531165

Inside runThisScriptX.sh, you should wait for the parallel children to complete before exiting:

child1 &
child2 &
child3 &
wait

Then in OuterMostShellScript.sh, you run runThisScriptX.sh itself in the background, and wait for it.

some commands
./runThisScriptX.sh &
wait
other commands
end of script.

wait can only be used to wait on processes started by the current shell.

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201447

Use the bash built-in wait; from the man page -

Wait for each specified process and return its termination status. Each n may be a process ID or a job specification; if a job spec is given, all processes in that job's pipeline are waited for. If n is not given, all currently active child processes are waited for, and the return status is zero. If n specifies a non-existent process or job, the return status is 127. Otherwise, the return status is the exit status of the last process or job waited for.

Or, don't background the tasks.

Upvotes: 1

devnull
devnull

Reputation: 123508

Two things:

  • Source your script
  • Use wait

Your script would not look like:

some commands
. ./runThisScriptX.sh          # Note the leading . followed by space
wait                           # This would wait for the sourced script to finish
other commands
end of script

Upvotes: 4

Jonathan Leffler
Jonathan Leffler

Reputation: 753755

Use the wait built-in command:

wait

This waits for all background processes started directly by the shell to complete before continuing.

Upvotes: 1

Related Questions