How do Ctrl+Z, bg, fg and jobs work in a shell?
Ctrl+Z suspends the foreground job, bg resumes it in the background, fg brings it back to the foreground and jobs lists the shell's jobs with numbers. Appending & to a command starts it in the background directly.
Explain it simply
Suppose you are copying a big folder and suddenly need the terminal for something else. You do not have to wait or open another window.
- Press Ctrl+Z. The shell pauses the program and prints something like
[1]+ Stopped. - Type bg to let it continue running in the background, or leave it paused.
- Type jobs to see the list:
[1]+ Running cp -r big/ backup/ &. - Type fg %1 to bring job 1 back to the foreground.
bg %2 and kill %2 also accept job numbers. Starting with & skips the first step: sleep 300 &.
These jobs belong to your current shell. Close the terminal and the shell sends them a hangup signal (SIGHUP), which usually ends them. For jobs that must survive logout, use nohup, disown, tmux or screen.
Example
sleep 300
# press Ctrl+Z
# [1]+ Stopped sleep 300
bg
# [1]+ sleep 300 &
jobs
# [1]+ Running sleep 300 &
fg %1What to say in the interview
"Ctrl+Z suspends the foreground job, bg continues it in the background, fg brings it back and jobs lists them. They are tied to the shell, so for work that must survive a logout I use nohup or tmux."
Common mistakes
- Thinking a background job keeps running after the terminal closes; it often receives SIGHUP.