C.W.K.
Stream
Lesson 04 of 10 · published

Job Control: bg, fg, jobs

~10 min · jobs, bg, fg

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

Run a thing without blocking the prompt

Append & to put a command in the background of your shell. The prompt returns immediately; the job keeps running. jobs lists what your shell knows about; fg brings one back to the foreground; bg resumes a stopped job in the background.

The flow

./long-build.sh &        # start in background
jobs                          # list with [N] tags
fg %1                         # bring job 1 to foreground
Ctrl+Z                        # suspend it
bg %1                         # resume in background
fg %1                         # back to foreground
kill %1                       # end it

Job IDs vs PIDs

%1 = job 1 of this shell. kill %1 kills it. jobs -l shows the underlying PIDs if you want to use them with ps or kill from another shell.

Disowning

By default, when you close the terminal, the shell sends SIGHUP to all its jobs. disown %1 detaches the job so it survives the shell's death. nohup ./script & at start does the same plus redirects output to nohup.out.

When to reach for tmux instead

For long-running things you might want to come back to tomorrow, use a tmux session (next-but-one lesson). Job control is for the now-and-here; tmux is for multi-session persistence.

Code

Practice the flow·bash
sleep 60 &
sleep 60 &
jobs                  # [1] [2]
fg %1                 # foreground
# Press Ctrl+Z
bg %1                 # back to bg
kill %1 %2            # end both

External links

Exercise

Run sleep 30 & three times. jobs to list them. fg %2 brings the second to the foreground. Ctrl+Z to suspend. bg %2 to resume. Then kill %1 %2 %3.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.