Capturing Process IDs with $! and $$
Every process on a Unix-like system has a process ID (PID), a positive integer that the kernel assigns when the process starts and that identifies it until it ends. Tools that work with processes, such as wait, kill and ps, take PIDs as arguments, so a script that manages processes needs a way to learn them. Bash provides two special parameters for this:
$$expands to the PID of the shell itself: the script, or your interactive shell.$!expands to the PID of the most recent background job started with&.
Two related variables complete the picture: $BASHPID is the PID of the current Bash process, which differs from $$ inside subshells, and $PPID is the PID of the shell's parent process. Lesson 43 introduced these parameters briefly; this lesson shows how they behave in detail and how scripts use them.
$$: The Shell's Own PID
$$ is set once, when the shell starts, and stays the same for the whole script:
echo "script: \$\$=$$ BASHPID=$BASHPID PPID=$PPID"
( echo "subshell: \$\$=$$ BASHPID=$BASHPID" )
echo "cmd subst: $(echo "\$\$=$$ BASHPID=$BASHPID")"
echo "pipeline: " | { read -r x; echo "pipe part: \$\$=$$ BASHPID=$BASHPID"; }
bash -c 'echo "child bash: \$\$=$$ PPID=$PPID"'
script: $$=835 BASHPID=835 PPID=832
subshell: $$=835 BASHPID=837
cmd subst: $$=835 BASHPID=838
pipe part: $$=835 BASHPID=840
child bash: $$=841 PPID=835
Reading the output line by line:
- In the main script,
$$and$BASHPIDare equal.$PPIDis the process that started the script, here the shell that ranbash a.sh. - A
( )subshell, a command substitution$( )and a part of a pipeline are separate processes, each with its own PID, shown by$BASHPID. Yet$$still shows the main script's PID. POSIX defines$$this way, so that a whole script, including its subshells, can refer to one stable ID. bash -cstarts a new shell, not a subshell, so it has its own$$, and its$PPIDis the script.
The practical rule: use $$ when you mean "this script", and $BASHPID when you really need the PID of the exact process that is running the current line.
Uses of $$
Identifying log lines. When several copies of a script may run at the same time, putting $$ into each log line shows which copy wrote it:
log() { printf '%s [%d] %s\n' "$(date +%T)" "$$" "$*" >&2; }
log "starting"
( log "from a subshell, BASHPID $BASHPID" )
12:58:52 [996] starting
12:58:52 [996] from a subshell, BASHPID 1008
Both lines carry the same script ID, as intended.
Signalling the script itself. kill -USR1 $$ sends a signal to the script from inside a subshell or background job; lesson 138 used this to interrupt wait.
Temporary file names. Older scripts often name temporary files after the PID:
echo "/tmp/report.$$"
/tmp/report.996
The name is unique among running processes, but it is predictable: another user can guess it and create the file (or a symbolic link with that name) before the script does. mktemp (lesson 113) creates a file with a random name safely and should be used instead. $$ is still fine for names that do not need to be secret, such as a log tag.
$!: The PID of the Last Background Job
$! is set each time a command is started with &. Save it right away, because the next & replaces it:
echo "\$! before any job: '${!-unset}'"
sleep 1 & first=$!
sleep 1 & second=$!
echo "first=$first second=$second \$!=$!"
ps -o pid=,comm= -p "$first,$second"
$! before any job: 'unset'
first=842 second=843 $!=843
842 sleep
843 sleep
Before the first background job, $! is unset, so ${!-unset} printed the fallback word. With set -u (lesson 120), a plain $! at that point would stop the script with an "unbound variable" error.
Foreground commands do not change $!:
true; ls / > /dev/null; echo "still $!"
still 843
What $! Points To
$! is the PID of one process, but a background job may consist of several. Which one does $! identify?
For a pipeline, it is the last command of the pipeline:
sleep 1 | sleep 2 &
ps -o pid=,args= -p $!
847 sleep 2
For a group or compound command, { ...; } &, Bash forks a subshell to run the group, and $! is that subshell, not the commands inside it:
{ sleep 1; echo; } > /dev/null &
ps -o pid=,args= -p $!
852 bash a.sh
The process with PID $! is a copy of the script (bash a.sh), and the sleep is its child. This difference matters when the PID is used with kill (lesson 140). Killing the subshell does not kill its children:
{ sleep 30; } &
gpid=$!
sleep 0.2
ps -o pid=,ppid=,args= --ppid "$gpid"
kill "$gpid"; wait "$gpid"; echo "group subshell status $?"
ps -o pid=,ppid=,args= -C sleep
1000 998 sleep 30
group subshell status 143
1000 1 sleep 30
The subshell (998) ended with status 143 (SIGTERM), but sleep 30 kept running and was adopted by process 1. When a background job is a single long command, exec inside the group makes the command replace the subshell, so $! is the command itself:
{ exec sleep 30; } &
ps -o pid=,args= -p $!
1004 sleep 30
A plain sleep 30 & behaves the same way, because Bash runs a simple background command directly in the forked child.
Process substitution sets $! as well. In Bash 5.2, after cat <(echo from procsub), $! held the PID of the process that ran echo, so a script that uses <( ) between starting a job and reading $! gets the wrong PID. Saving $! in a variable immediately after & avoids all such surprises.
Using a Saved PID
A saved PID is used with the tools from the neighbouring lessons:
| Task | Command | Lesson |
|---|---|---|
| Wait for the job and get its status | wait "$pid" | 138 |
| Check whether the process still exists | kill -0 "$pid" | 140 |
| Stop it | kill "$pid" | 140 |
| Show information about it | ps -o pid,stat,etime,args -p "$pid" | 143 |
kill -0 sends no signal at all; it only checks whether the process exists and whether you may signal it, and returns 0 or 1 accordingly. It is the standard "is it still running?" test.
PID Files
A PID only lives as long as the shell variable that holds it. To manage a background process from another run of a script, for example "start" now and "stop" later, the PID is written to a PID file. Two problems have to be handled:
- The process may have ended, leaving a stale PID file.
- PIDs are reused. After the process ends, the kernel can give the same number to an unrelated process, and a script that blindly signals the PID from the file could hit that process.
The complete example below checks both.
A Complete Example: Start, Status and Stop
ticker.sh stands in for a long-running service. It writes a line every second and stops cleanly on SIGTERM:
#!/usr/bin/env bash
# ticker.sh: a stand-in for a long-running service; logs a line every second.
echo "ticker $$ started"
trap 'echo "ticker $$ stopping"; exit 0' TERM
while :; do
echo "tick $(date +%T)"
sleep 1 & wait $!
done
sleep 1 & wait $! instead of a plain sleep 1 lets the TERM trap run immediately, because a trapped signal interrupts wait but not a foreground command (lesson 138).
svc.sh starts the ticker in the background, records its PID, and later reports its status or stops it:
#!/usr/bin/env bash
# svc.sh start|status|stop: run ticker.sh in the background and track it
# through a PID file.
set -uo pipefail
dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
pidfile=$dir/ticker.pid
logfile=$dir/ticker.log
read_pid() { # print the recorded PID if it is ours and alive
local pid
[[ -r $pidfile ]] || return 1
read -r pid < "$pidfile" || return 1
[[ $pid =~ ^[0-9]+$ ]] || return 1
kill -0 "$pid" 2>/dev/null || return 1 # process exists?
[[ $(ps -o args= -p "$pid") == *ticker.sh* ]] || return 1 # still ours?
echo "$pid"
}
case ${1-} in
start)
if pid=$(read_pid); then echo "already running (PID $pid)"; exit 0; fi
nohup bash "$dir/ticker.sh" >> "$logfile" 2>&1 < /dev/null &
echo "$!" > "$pidfile"
echo "started (PID $!), launched by svc.sh PID $$"
;;
status)
if pid=$(read_pid); then echo "running (PID $pid)"
else echo "not running"; exit 3; fi
;;
stop)
if ! pid=$(read_pid); then echo "not running"; rm -f -- "$pidfile"; exit 0; fi
kill "$pid"
for (( i = 0; i < 50; i++ )); do # up to 5 seconds
kill -0 "$pid" 2>/dev/null || break
sleep 0.1
done
if kill -0 "$pid" 2>/dev/null; then echo "PID $pid did not stop" >&2; exit 1; fi
rm -f -- "$pidfile"
echo "stopped (PID $pid)"
;;
*)
echo "usage: ${0##*/} start|status|stop" >&2; exit 2
;;
esac
How It Works
startlaunches the ticker withnohup(lesson 135), so it ignores the hangup signal when the terminal closes, and redirects all three standard streams so it does not depend on the terminal. Right after&,$!is written to the PID file.$$in the message is the PID ofsvc.shitself, which ends a moment later; the ticker keeps running.read_pidaccepts the PID file only if it contains a number,kill -0confirms that such a process exists, andps -o args=shows that the process is still runningticker.sh. The last check protects against PID reuse.statusexits with 3 when the service is not running, the code that Linux init scripts use for "program is not running", so other scripts can test it.stopsends SIGTERM and then polls withkill -0every 0.1 seconds, for up to 5 seconds, until the process is gone. A script cannotwaithere, because the ticker is not a child of this run ofsvc.sh; it was started by an earlier run.
Running the Complete Example
The scripts were placed in /home/ana/svc:
$ bash svc.sh start
started (PID 1019), launched by svc.sh PID 1015
$ bash svc.sh start
already running (PID 1019)
$ bash svc.sh status
running (PID 1019)
$ ps -o pid=,ppid=,args= -p "$(cat ticker.pid)"
1019 1 bash /home/ana/svc/ticker.sh
$ bash svc.sh stop
stopped (PID 1019)
$ bash svc.sh stop
not running
$ cat ticker.log
ticker 1019 started
tick 12:58:57
tick 12:58:58
tick 12:58:59
ticker 1019 stopping
The status check ran about two seconds after the start. ps shows a parent PID of 1: svc.sh had already exited, so the ticker was adopted by process 1, as lesson 135 described for background jobs that outlive their script. In the log, the ticker's own $$ (1019) matches the PID that svc.sh recorded from $!.
Stale and invalid PID files are recognized. In each case status printed not running and exited with 3:
Content of ticker.pid | Why it is rejected |
|---|---|
1 | process 1 exists, but its command line does not contain ticker.sh |
999999 | no such process (kill -0 fails) |
abc | not a number |
PID of a ticker ended with kill -9 | the process is gone; the TERM trap never ran, so the file was left behind |
An unknown command such as bash svc.sh restart printed the usage line and exited with 2. Real services are usually managed by a service manager such as systemd, which tracks processes without PID files, but the same techniques remain useful for small tools, development servers and scripts on systems without one.