iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Background Jobs & nohup

A backgrounded job keeps running while you do other work in the same shell. The trio to know is &, jobs, and fg. The trap is that backgrounded jobs are tied to your shell session — close the terminal and they die unless you detach them with nohup, disown, setsid, or run them under a real supervisor like systemd, tmux, or screen.

Backgrounding, foregrounding, and detaching jobs

EXAMPLE
# 1) Start a job in the background
sleep 300 &        # & forks and prints [1] 12345  (job number 1, PID 12345)

# 2) See what is running
jobs               # [1]+ Running   sleep 300 &
jobs -l            # also shows PIDs

# 3) Bring it back to the foreground
fg %1              # by job number; or 'fg' for the last job

# 4) Suspend and resume the foreground job
# (press Ctrl+Z to suspend; you'll see 'Stopped')
bg %1              # resume the most recent stopped job in the background

# 5) Kill a job by number
kill %1
kill -9 %1         # SIGKILL when polite signals are ignored

# 6) Run something that survives logout
nohup ./long-job.sh > job.log 2>&1 &
disown -h %1        # prevent SIGHUP being sent at shell exit (works in bash)
setsid ./long-job.sh > job.log 2>&1 < /dev/null &  # new session, fully detached

# 7) Tee the output AND background AND survive logout
( ./build.sh 2>&1 | tee build.log ) >/dev/null 2>&1 &
disown

# 8) For anything you actually want reliable, use a supervisor:
tmux new -d -s build './build.sh; sleep 5'
# OR systemd-run --user --unit=build './build.sh'

Why it matters

For production-style long runs, lean on tmux/systemd over nohup+disown. They survive ssh disconnects, capture logs, restart on crash, and give you a way to reattach and inspect — three things nohup quietly does not.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
long-task &                    # background
jobs; fg %1; bg %1
nohup long-task &              # survives logout
Try it Yourself »

Discussion

Loading…