← Back to Bash Course | Chapter 11: Process Management | Lesson 4 of 12

Process IDs and the ps Command

Every running program on the system has a unique number called a process ID, and the ps command lets you list which programs are running and what their numbers are.

The Current Shell's PID

$$ always expands to the process ID of the current shell instance running the script, useful for building unique temp filenames or logging which process did something.

Example: The Current Shell's PID

bash
#!/bin/bash
echo "this script's PID is $$"
tmpfile="/tmp/scratch_$$.txt"
echo "hello" > "$tmpfile"
cat "$tmpfile"
rm -f "$tmpfile"

Inspecting a Process with ps

ps -p PID -o field1,field2 prints only the requested columns for a specific process, which is far more reliable for scripts than parsing the default, loosely formatted ps output.

Example: Inspecting a Process with ps

bash
#!/bin/bash
ps -p $$ -o pid,ppid,comm

Checking a Background Job's PID

After starting a background job, both $! (the PID) and ps -p (to confirm it exists and inspect it) can be used together to verify a job is actually running before waiting on it.

Example: Checking a Background Job's PID

bash
#!/bin/bash
sleep 0.3 &
pid=$!
if ps -p "$pid" > /dev/null; then
    echo "job $pid is running"
fi
wait "$pid"
if ! ps -p "$pid" > /dev/null 2>&1; then
    echo "job $pid has finished and is gone"
fi
Common Mistakes
  1. Assuming $$ refers to a background job's PID; $$ always refers to the CURRENT shell's own PID, not any child process.
  2. Confusing $$ (current shell PID) with $BASHPID, which reflects the PID of the actual subshell when inside one, while $$ still reports the original shell in some contexts.
  3. Parsing ps output with fragile column-position assumptions instead of using ps -o to request exactly the fields needed in a stable format.
Chapter Summary
  • $$ expands to the current shell's own process ID.
  • $! expands to the most recently backgrounded job's PID, not the current shell's.
  • ps -p PID -o pid,ppid,cmd prints specific fields for one process in a predictable format, good for scripting.
  • ps without arguments typically shows only processes attached to the current terminal session.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.