You wait for a background command when you need its result: the shell returns the prompt when the command finishes.
wait waits for a background job of this shell, and wait $! for the last background command. How the command ended the shell records in the $? variable: this is the exit status. 0 means success, any other number means an error or an interruption. After Ctrl+C, for example, $? holds 130.
After five seconds the shell prints Done for the job, and echo $? prints 0. $? holds the status of the last command that ran, so you print it right away.
You found someone else's process with PID 1500 in ps and ran wait 1500. What will the shell print?
-
waitlearns exit statuses from its own jobs. About someone else's process it reportsis not a child of this shell, and$?is 127. -
waitends nothing; it waits. About a process this shell did not start,waitreportsis not a child of this shell. -
waitwaits for this shell's own jobs. About someone else's process it printspid 1500 is not a child of this shell.
wait waits for its own shell's jobs, the processes that shell started. For someone else's PID the shell prints is not a child of this shell.
Key points
-
wait $!returns the prompt when the last background command finishes. -
The exit status sits in
$?until the next command: 0 means success, any other number an error or an interruption.