I’ve been working with UNIX operating systems for 20+ years and I’m still amazed at how much I still don’t know about it. Recently at work I came across a script (Bourne) that made use of the wait command. Now if someone had asked me if a command like this existed I would probably have guessed yes, so I wasn’t completely shocked by it, but I was kinda surprised that I had never seen it actually used anywhere in the wild.
The wait command gives you the ability to block a script on the termination of another process or list of processes. This can come in handy when you want to make sure a program finished before you’re script moves on. Specifically for a program where it runs as a backgrounded process.
I like examples so here are a couple that demonstrate how wait works.
Example 1
1 2 3 4 5 6 7 8 9 10 |
# wait with a process id # run the sleep command for 15 seconds backgrounded % sleep 15 & [1] 8546 # wait for sleep's process id ($!) to finish, and then echo "hi" % wait $! && echo "hi" [1]+ Done sleep 15 hi |
Example 2
Additionally you can give wait the job id (%1, %2, etc.) instead.
1 2 3 4 5 6 7 |
# wait with a job id % sleep 15 & [1] 8551 % wait %1 && echo "hi" [1]+ Done sleep 15 hi |
Example 3
You can also drop the process id entirely if the wait command occurs right after the backgrounded command.
1 2 3 4 5 6 7 |
# wait without any argument % sleep 10 & [1] 8552 % wait && echo "hi" [1]+ Done sleep 10 hi |
Example 4
Finally you can tell wait to wait on more than one process.
1 2 3 4 5 6 7 8 9 10 |
# wait on 2 processes % sleep 10 & [1] 8570 % sleep 10 & [2] 8571 % wait %1 %2 && echo "hi" [1]- Done sleep 10 [2]+ Done sleep 10 hi |
For more information about the wait command check out the wait section of the Bash FAQ. Check out more about special variables in Bash.
NOTE: For further details regarding my one-liner blog posts, check out my one-liner style guide primer.
From Lâmôlabs
