DEV Community

Cover image for How to Use the wait Command in Bash
Dishang Soni for ServerAvatar

Posted on • Originally published at serveravatar.com

How to Use the wait Command in Bash

In Bash scripting, the wait command is commonly used when running commands in the background using the & symbol, allowing multiple tasks to execute concurrently. However, when the completion of one or more of those tasks is crucial for the next steps, the script must pause and wait.

This is where the ‘wait’ command comes in. It halts the script’s execution until a specific background process, or all background processes, have completed. This ensures smooth automation by preventing race conditions and execution conflicts.

Whether you’re downloading files, starting services, or managing timed operations, the ‘wait’ command helps keep reliable control over the flow of your script.

Prerequisites

  • A Linux environment or terminal with Bash installed
  • Basic knowledge of shell scripting
  • Access to create and execute ‘.sh‘ script files

Bash ‘wait’ Command Syntax and Common Options

You can use the ‘wait’ command in Bash with this basic syntax:

wait [pid ...]

How to Use the wait Command in Bash-ServerAvatar

Note: If no PID or job ID is specified, ‘wait’ pauses until all background processes are finished.

Single Process ‘wait’ Command

Description

When you use ‘&’, a command runs in the background. By default, the script continues executing. To pause the script until that background task finishes, use ‘wait’.

Steps to Execute

  1. Create a script file:

nano wait-single.sh

  1. Add the following code:

#!/bin/bash
echo "Starting background process..."
sleep 5 &
echo "Waiting for process to complete..."
wait
echo "Process finished."

  1. Save and exit (Press ‘Ctrl + O’ (then press ‘Enter’ to confirm the filename), then press ‘Ctrl + X’ to exit).

  2. Make the script executable:

chmod +x wait-single.sh

  1. Run the script:

./wait-single.sh

Read full article: https://link.srvr.so/soarzcuc

Top comments (0)