Wait command in Linux allows the system to wait for one or more processes and returns their exit status for further use. In this article, we will learn how to use wait command in Linux. It is available in almost every shell such as bash, csh, etc.
How to Use Wait Command in Linux
Here is the syntax of wait command
wait [options] id
In the above command you need to provide the process id or job id for whom the command needs to wait. If no id is specified then wait command will wait till all processes are completed.
Here is an example to wait for background process with PID 7435
wait 7435
If you provide multiple PIDs, then the command will wait for all listed processes to complete and return exit status of each process.
You can also use job id instead of process id. Let us say you run the following process in background.
$ echo "test" > /tmp/home/data.txt &
[2] 5437
The above command will return the job id in square brackets [] followed by process id. You can wait for the above job to complete using the following command.
$ wait %2
If you use -n option then wait command will wait for any of the listed process/jobs to complete and return its exit status.
$ wait -n 5443 2344 3122
If you don’t mention any id after -n option then wait command will wait for any background process to complete and return its exit status.
Also read : How to Run Multiple cURL requests in Parallel
Example script using wait
Here is a simple script that uses wait command.
#!/bin/bash rsync -a /data /remote/product & process_id=$! echo "PID: $process_id" wait $process_id echo "Exit status: $?"
Let us look at the above script line by line,
1. We first specify the shell to be used for execution (#!/bin/bash).
2. Then we run an rsync command in background.
3. The third line, saves the process id of the previous command executed, that is, the rsync command.
4. Then we echo the saved process id.
5. Next, we run the wait command for rsync command to complete.
6. Finally, we print the exit status of rsync command.
Also read : How to Stack Local Changes in Git Without Commit
Difference between wait and sleep
wait command makes shell wait for one or more processes while sleep command simply suspends execution cycle for specified amount of time.
wait command depends on completion of other processes to stop waiting, while sleep does not depend on any other process for it to stop sleeping.
Also read : How to Convert Webpage into PDF in Python
Conclusion
In this article, we have learnt how to use wait command in Linux. wait command waits for one or more processes/jobs to complete and returns their exit status. It is useful to run processes/jobs that depend on other processes to complete.
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.