Bash “wait” Command in Process Management [6 Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Using the “wait” command in Bash implies pausing the execution of a script until the background processes or jobs are completed. This command plays a crucial role in process management offering proper synchronization, error handling, flexible waiting, and proper termination capabilities for background processes.

In this article, I’ll show you how to use the “wait” command in Bash process management with different examples. Let’s delve into it!

What is “wait” Command in Bash?

The “wait” command is a built-in Bash shell command that waits for the completion of background processes launched within a script. It allows blocking the execution of the script until all the background processes get terminated. The basic syntax of the “wait” command is:

wait [PID]

Here, PID specifies the Process IDs of the background processes to wait for. If no PID is specified, the command waits for all background processes to complete.

6 Examples of Bash “wait” Command in Process Management

The “wait” command can be used in various scenarios in Bash Process Management. Following are 6 different examples of using the “wait” command in Bash such as waiting for a single background process, multiple background processes, the first background process, the background process within pipelines, and loops, and the trapping and executing cleanup actions.

1. Waiting for a Single Background Process in Bash

To wait for a single process to complete while it is running in the background, use the “wait” command like the following script:

#!/bin/bash

#Launching a background process
sleep 5 &
echo "A background process is running"
wait
echo "Process execution completed!"
EXPLANATION

Here, sleep 5 & pauses the script’s execution for 5 seconds. Next, the script prints the line ‘A background process is running’ employing the echo command. wait waits for the background process (sleep 5 &) to complete. Finally, the script prints a message indicating a successful execution of the process.

Waiting for a Single Background Process in Bash

The above image indicates that the process execution has been completed successfully.

2. Waiting for Multiple Background Processes in Bash

When multiple processes are running in the background, use the “wait” command without any argument (PID) to wait for all the processes to complete.

Here’s a script to wait for multiple processes in Bash:

#!/bin/bash

#Launching multiple background processes
sleep 2 &
sleep 3 &
sleep 4 &

echo "Multiple background processes are running"

#Waiting for all background processes to finish
wait

echo "Process execution completed!"
EXPLANATION

Here, sleep 2 &, sleep 3 & and sleep 4 & pause the script’s execution for 2, 3 and 4 seconds. Then, the script prints ‘Multiple background processes are running’ using the echo command. Next, wait waits for all the background processes to finish. Lastly, the script prints ‘Process execution completed!’.

Waiting for Multiple Background Processes in Bash

This image shows that all the process executions have been completed successfully.

Waiting for Multiple Processes with Specific PIDs

As each process running in the background includes a specific PID, you can use them as arguments of the “wait” command to wait for all those particular background processes to complete.

Check out the following script to wait for multiple background processes with specific PIDs:

#!/bin/bash

#Launching multiple background processes
sleep 3 &
pid1=$!  #Storing PID of the process
echo "Executing the first process with PID: $pid1"

sleep 6 &
pid2=$!  #Storing PID of the process
echo "Executing the second process with PID: $pid2"

#Waiting for specific background processes to finish
wait $pid1  #Waiting for the first process to finish
echo "First task completed."

wait $pid2  #Waiting for the second process to finish
echo "Second task completed."

echo "Process executed successfully"
EXPLANATION

In the script, sleep 3 & and sleep 6 & are the two background processes that pause the script’s execution for 3 and 6 seconds. pid1=$! and pid2=$! capture the PIDs of the two processes using the special variable $!. Next, wait $pid1 and wait $pid2 wait for each background process to complete individually.

Waiting for Multiple Processes with Specific PIDs

From the image, you can see that all the processes with particular PIDs have been completed.

3. Waiting for Background Process within Pipelines

Piping (|) is helpful to run commands or processes sequentially in Bash. When you chain multiple processes using the pipe operator and use the “wait” command, the script waits for all background processes in the pipeline to complete before continuing the execution.

For example, first, create a file and add text:

file1.txt >

Linux distros:

Ubuntu
Red Hat
CentOS
Kali Linux

Now, see the following script to wait for the background process within pipelines in Bash:

#!/bin/bash

process1() {
    cat file1.txt
}
process2() {
    grep "Linux"
}
process3() {
    wc -l > file2.txt
}

#Starting pipelines
process1 | process2 | process3 &

#Waiting for the background process to finish
wait

echo "Process completed"
EXPLANATION

The script defines three different functions process1(), process2() and process3() where process1() reads the contents of the file1.txt, process2() searches for lines containing the word ‘Linux’ using the grep command and process3() counts the number of lines using wc -l command and writes it to file2.txt. Then, in process1 | process2 | process3 &, the output of process1 is piped into process2, and the output of process2 is piped into process3 and the pipeline is executed in the background. Finally, wait waits for the piped process to complete.

Waiting for Background Process within Pipelines

The image states that all processes in the pipeline have been completed.

4. Waiting for the First Process to Complete in a Bash Script

By default, the “wait” command waits for all background processes to finish. However, when the -n option is used with the “wait” command, it pauses the script’s execution and waits until any one of the background processes completes. After the process completion, the script continues its execution.

Check out the script below to wait for the first process to complete in Bash:

#!/bin/bash

#Simulating background process using a function
child_process() {
    local id=$1
    echo "Started child $id"
    sleep $((RANDOM % 6 + 1)) 
    echo "Completed child $id"
}

echo "Starting parent process $$"

#Starting three background processes
child_process 1 &
pid1=$!

child_process 2 &
pid2=$!

child_process 3 &
pid3=$!

#Waiting for the first background process to finish
wait -n

echo "Completed parent process's wait"
EXPLANATION

Here, the function child_process() defines a local variable id and assigns the value of the first argument passed to the function to it using the special variable $1, prints a message indicating the start of the task with the given ID, sleeps for a random duration between 1 and 6 seconds, and then prints a message indicating the completion of the task.

Next, echo "Starting parent process $$" indicates the starting of the parent process where $$ represents the PID of the current script. Then, the script starts three background processes and stores their PIDs using $!. Finally, wait -n waits for the first background task to finish rather than waiting for all of them.

Waiting for the First Process to Complete in a Bash Script

The image shows that the wait command exited after the completion of the first child process.

5. Iterative Waiting for Processes within a Loop

The “wait” command within a loop allows users to execute multiple background processes iteratively and wait for all the processes to finish before completing the script’s execution. It is useful to execute a similar task several times in a loop in Bash.

Following is an example of using the wait command within a loop in Bash:

#!/bin/bash

#Starting a loop
for n in {1..4}; do
    sleep $n &  #Sleeping for the value of $n seconds in the background
done

echo "Starting background processes"

#Waiting for all background processes to finish
wait

echo "Completed all background processes"
EXPLANATION

Here, for n in {1..4}; do runs 4 iterations with the variable n that takes values from 1 to 4. Then, the background process sleep $n & pauses the script for the value of n seconds. Finally, wait waits for all the background processes started within the loop to finish.

Iterative Waiting for Processes within a Loop

From the above image, you can see that all the background processes have been executed successfully.

6. Trapping and Executing Cleaning-up Actions

In Bash, the trap command is used to handle signals received by the script. It ensures proper clean-up of the background processes when receiving particular signals like SIGINT (CTRL + C) or SIGTERM. Often, the combination of trap and the “wait” command can be useful for handling signals and controlling background processes.

Go through the script below to handle interruptions gracefully in Bash:

#!/bin/bash

#Starting a process in the background
sleep 10 &

#Storing the PID of the process
pid=$!

#Trapping SIGINT signal and killing the background process
trap "kill $pid" SIGINT

echo "Running background process"

#Waiting for the background process to finish
wait $pid

echo "Completed the process"
EXPLANATION

Here, sleep 10 & starts a background process causing the script to pause for 10 seconds and pid=$! stores the PID of the background process. Then, trap 'kill $pid' SIGINT sets up a trap to catch the SIGINT signal and terminates the background process associated with the PID. wait $pid waits for the background process to finish.

Trapping and Executing Cleaning-up ActionsFrom the image, you can see that when I have pressed CTRL + C to send the SIGINT signal, the trap catches it and terminates the background process displaying a message of indication ‘Completed the process’. In this case, the “wait” command won’t wait for the background process to complete.

Conclusion

To sum up, the “wait” command is a powerful and easy-to-use command for managing background processes in Bash scripts. Mastering this command increases reliability, synchronizes processes, and simplifies workflow management during Bash scripting.

People Also Ask

What does the wait command do?

The wait command pauses the execution of a Bash script until all background processes within the script are completely executed. It ensures that the script will not continue until the background processes have finished running. You can use the ‘wait’ command to schedule the execution of the tasks that are running in parallel and make sure that everything is running in the correct order within the script.

Can multiple wait commands be used sequentially?

Yes, multiple ‘wait’ commands can be used sequentially in Bash where each ‘wait’ command using the PIDs waits for the corresponding background processes to finish by employing syntaxes like wait $PID1, wait &PID2, wait $PID3.

How do you wait 10 seconds in Linux shell?

To wait for 10 seconds in Linux shell, you can use the sleep command with an ampersand & at the end. For example:

#!/bin/bash

#Starting a background process that sleeps for 10 seconds
sleep 10 &

#Waiting for the background process to finish
wait

echo "Waiting for 10 seconds completed."

Is the wait command suitable for handling asynchronous operations in Bash?

Yes, the ‘wait’ command is suitable for handling asynchronous operations in Bash because it provides flexibility in waiting for specific processes, synchronizes script executions, and provides efficient error handling which is very crucial for process management.

How do you specify which background processes to wait for with the wait command?

To specify which background processes to wait for, you can use the PIDs of the processes as arguments to the ‘wait’ command. For example:

#!/bin/bash

#Launching a background process
sleep 4 &
pid1=$!  #Storing the PID

#Launching another background process
sleep 2 &
pid2=$!  #Storing the PID

#Waiting for the specified background processes to complete
wait $pid1 $pid2

echo "All processes completed."

Related Articles


<< Go Back to Process Management in Bash | Bash Process and Signal Handling | Bash Scripting Tutorial

Rate this post
Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment