🎓 A1Learner
🔍
0 of 45 lessons completed

Bash Detached Jobs

A detached job is a background job that keeps running after its parent shell exits. Detachment breaks the link between the job and the shell that started it, so closing the shell does not stop the work.

nohup survives a hangup

The job writes its result to a file instead of the terminal. Input comes from nowhere and output goes to a log, so the job needs no terminal at all.

nohup bash -c 'echo detached work done > result.txt' </dev/null >nohup.log 2>&1 &
pid=$!
wait "$pid"
cat result.txt

disown removes a job from the table

The jobs command lists nothing after disown, yet the job still finishes. The table entry is gone, but the work is not.

bash -c 'sleep 0.2; echo done > disowned.txt' &
disown
jobs
echo "table checked"
sleep 0.4
cat disowned.txt

setsid starts a new session

The job runs under setsid, so it belongs to a new session. Its result still lands in a file the script can read.

setsid bash -c 'echo session work done > session.txt' &
pid=$!
wait "$pid"
cat session.txt

Example

printf 'line one\nline two\n' > input.txt
nohup bash -c 'while read -r line; do echo "logged: $line"; done < input.txt > logged.txt; printf done > finished.txt' </dev/null >worker.log 2>&1 &
disown
until [ -f finished.txt ]; do sleep 0.05; done
echo "shell moved on"
cat logged.txt

Key points

  • nohup: run a job immune to hangup signals, so it survives a closing terminal.
  • disown: remove a running job from the shell's job table, so the shell forgets it at exit.
  • setsid: start a job in a new session, so it leaves the parent's process group entirely.
  • Output rule: a detached job must redirect its output to a file, or it writes to a lost terminal.
  • No wait after disown: a disowned job leaves the job table, so wait cannot track it; synchronize on a file the job writes instead.
  • Honest limit: detachment does not protect a job from a reboot or from being killed directly.
  • Order rule: redirect first, then launch, then disown, so no output is lost in between.

In this example, the script first writes two input lines to a file. It then launches a worker under nohup with no terminal attached, and disown removes the worker from the job table. A disowned job cannot be waited on, so the script watches for the finished file the worker writes. It then prints that the shell moved on, and the logged file shows both lines processed.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which command removes a running job from the shell's job table?