wait – Returns After Waiting for the Process to Finish Executing

The wait command in Linux is used to pause the execution of a shell until one or more of its child processes complete their execution. It waits for the process to finish executing and then returns the exit status of the completed process. This command is useful when you need to wait for a specific process to finish before running another command or script.

Overview

The wait command is used in combination with other commands or scripts that spawn child processes. When a child process is spawned, it is assigned a unique process ID (PID). The wait command can be used to wait for a specific child process to complete its execution by specifying the PID of the child process.

The syntax for the wait command is as follows:

wait [PID]

where PID is the process ID of the child process to wait for. If PID is not specified, the wait command will wait for all child processes to complete their execution.

Example 1

Suppose you have a script myscript.sh that spawns a child process child_process.sh. You can use the wait command to wait for child_process.sh to finish executing before continuing with the rest of the script:

#!/bin/bash

./child_process.sh &
wait $!
echo "Child process has finished executing"

In this example, the & character is used to run child_process.sh in the background, and $! is used to get the PID of the child process. The wait command then waits for the child process to finish executing before continuing with the rest of the script.

Example 2

Suppose you have a script myscript.sh that spawns multiple child processes. You can use the wait command to wait for all child processes to finish executing before continuing with the rest of the script:

#!/bin/bash

./child_process1.sh &
./child_process2.sh &
./child_process3.sh &

wait
echo "All child processes have finished executing"

In this example, the wait command is used without specifying a PID, which causes it to wait for all child processes to finish executing before continuing with the rest of the script.

Options

The wait command does not have any options.

Troubleshooting Tips

  • If you specify an invalid PID, the wait command will return an error message.
  • If you use the wait command without spawning any child processes, the shell will be paused indefinitely.

Notes

  • The wait command is a built-in command in most shells, including Bash, Zsh, and Ksh.
  • The wait command only works with child processes that are spawned by the current shell. It cannot be used to wait for processes that are spawned by a different shell or by another user.