Bash Tutorial · Linux System Skills · Lesson 25 of 30

Bash Processes and Jobs

List processes, run commands in the background, wait for them, and stop them with signals.

Create a free account to save this page, take notes and track your progress. Sign in

Background jobs

cmd & runs a command in the background; $! is its process ID; wait waits for background jobs. In a terminal, jobs, fg and bg manage them, and Ctrl+Z suspends the foreground job.

Running tasks in parallel
start=$(date +%s%N)
for task in 1 2 3; do
  ( sleep "1.$task"; echo "task $task done" ) &
done
wait
elapsed_ms=$(( ($(date +%s%N) - start) / 1000000 ))
(( elapsed_ms < 2000 )) && echo "all tasks finished in under 2s (one after another they'd take 3.6s)"

Output

task 1 done
task 2 done
task 3 done
all tasks finished in under 2s (one after another they'd take 3.6s)

Run this on your computer — see “Get Started” for setup.

Processes and signals

  • ps aux lists processes; pgrep -f name finds them; top/htop show live usage.
  • kill PID sends SIGTERM (please stop); kill -9 PID sends SIGKILL (stop now, no cleanup). Try TERM first.
Sending signals
sleep 30 &
pid=$!
kill -0 "$pid" && echo "process is running"
kill -TERM "$pid"
wait "$pid" 2>/dev/null || echo "stopped with status $? (128 + 15 = SIGTERM)"

Output

process is running
stopped with status 143 (128 + 15 = SIGTERM)

Run this on your computer — see “Get Started” for setup.

Test yourself

Why try kill (SIGTERM) before kill -9?

  1. SIGTERM is faster
  2. SIGTERM lets the program clean up; SIGKILL stops it immediately
  3. kill -9 doesn't work on Linux
  4. There is no difference
Show answer

Answer: SIGTERM lets the program clean up; SIGKILL stops it immediately

Was this page helpful?