How to Wait for Background Process in Bash

Sheeraz Gul Feb 02, 2024
How to Wait for Background Process in Bash

This tutorial demonstrates how to wait for the background process in Bash.

Bash Wait for Background Process

The wait command in Bash can be used to wait for all the background processes to complete. This command will wait for the process and return the exit status.

The wait command will affect the current shell execution environment, which is why it is built-in in Bash and other shells.

The syntax for the wait command is:

wait [Options] BackgroundProcessID

Where the BackgroundProcessID id is the process or job. The wait command will wait till all the processes and subprocesses are completed for the given ID.

A simple example of a wait command can be:

wait 1234

The above command will wait for the background process 1234. We can also give multiple processes, and then the wait command will wait for all the background processes.

Now let’s run a process in the Background process:

rsync -a /mn/c/Users/Sheeraz &

The above command will run a process in the background and return the job and process id. See the output:

[1] 37

Where is job id is 1 and the process id is 37.

Now to wait for the job, we run the following command:

wait %1

Where 1 was the job id. The output for this command is:

[1]+  Exit 23                 rsync -a /mn/c/Users/Sheeraz

And to wait for the process, we use the following command:

wait 37

The above command will wait for the background process 37 to complete. Most of the time, the wait command is used in the Bash script files, spawning the background processes executed in parallel.

Here is an example of the script file:

#!/bin/bash
sleep 30 &
ProcessId=$!
echo "PID: $ProcessId"
wait $ProcessId
echo "Exit status: $?"

Running this script will output the process ID and exit status for the background process. See the output:

PID: 50
Exit status: 0
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Bash Background