Linux Labs

Users, permissions, and processes / Stage 11 of 13

Background jobs and the terminal

Not running Starting usually ~20 s
Leave the lesson

Step 5 of 7 · on a machine · 3 min

Wait for the result

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.

bash
sleep 5 &
wait $!
echo $?

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.

Check yourself 1 question

You found someone else's process with PID 1500 in ps and ran wait 1500. What will the shell print?

  • wait learns exit statuses from its own jobs. About someone else's process it reports is not a child of this shell, and $? is 127.

  • wait ends nothing; it waits. About a process this shell did not start, wait reports is not a child of this shell.

  • wait waits for this shell's own jobs. About someone else's process it prints pid 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.
Ubuntu 24.04
Loading…