>_ IzzyLab

Hands-on task

This task is step 24 of the course “Bash scripts: from a loop to a robust script”

Wait for a background job and grab its exit code

medium~5 min

The script /root/worker.sh runs for about a second and exits with return code 3. Run it in the background, wait for it to finish, and write its return code to /root/worker_rc.txt. You need to grab the code of that specific background process.

What you'll practise:
  • background processes
  • wait
  • $!
  • return codes
  • $?

Topic breakdown

The & at the end of a command sends the process to the background, and the shell continues without waiting for it. The shell puts the PID of the last launched background process into the special variable $!, and the return code of the last finished command into $?. The built-in command wait can block until a specific background process finishes by its PID and propagate its exit code — this lets you reliably grab the result of exactly the job you need, rather than some unrelated one.

What's checked

  1. background job's code obtained

What it looks like