Processes and Job Control
Prerequisites: How the shell runs commands
A running program is a process, identified by a process ID (PID). Bash can run processes in the background, wait for them, and stop them.
Viewing processes
# illustrative
ps aux | grep nginx
pgrep -a python
top # live view; press q to quit (or use htop)
Background jobs
Add & to run a command in the background, so you can keep working:
sleep 0.3 && echo "slow task finished" &
echo "started in the background"
wait
echo "all background jobs done"
started in the background
slow task finished
all background jobs done
&starts the command and returns immediately.waitpauses until background jobs finish.wait $pidwaits for one;$!holds the PID of the last background job.
Running tasks in parallel
task() { sleep "$2"; echo "$1 done"; }
task "download A" 0.6 &
task "download B" 0.2 &
task "download C" 0.4 &
wait
echo "All downloads finished"
download B done
download C done
download A done
All downloads finished
All three run at the same time, so the whole thing takes about 0.6 seconds (the longest task) instead of 1.2 seconds one after another — and each task reports as soon as it finishes, which is why B comes first.
Interactive job control
$ long-command # running in the foreground
^Z # Ctrl+Z pauses it
[1]+ Stopped long-command
$ bg # resume it in the background
$ jobs # list jobs
$ fg %1 # bring job 1 back to the foreground
Stopping processes: signals
kill sends a signal to a process:
kill PIDsendsSIGTERM— "please stop" (programs can clean up).kill -9 PIDsendsSIGKILL— stops it immediately, with no clean-up. Use it only when a program won't respond to a normalkill.pkill namesignals processes by name.- Ctrl + C sends
SIGINTto the foreground program.
Keeping jobs running after logout
A job started from a terminal usually stops when you log out. Use nohup command &, a terminal multiplexer such as tmux or screen, or —
for services — a proper service manager like systemd.