Process IDs and the ps Command
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
#!/bin/bash
echo "this script's PID is $$"
tmpfile="/tmp/scratch_$$.txt"
echo "hello" > "$tmpfile"
cat "$tmpfile"
rm -f "$tmpfile"
Login to try C/C++/Java/PHP code in the editor
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
#!/bin/bash
ps -p $$ -o pid,ppid,comm
Login to try C/C++/Java/PHP code in the editor
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
#!/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
Login to try C/C++/Java/PHP code in the editor
- Assuming
$$refers to a background job's PID;$$always refers to the CURRENT shell's own PID, not any child process. - 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. - Parsing
psoutput with fragile column-position assumptions instead of usingps -oto request exactly the fields needed in a stable format.
$$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,cmdprints specific fields for one process in a predictable format, good for scripting.pswithout arguments typically shows only processes attached to the current terminal session.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: