Capturing Process IDs with $! and $$

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 139 of 205

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 $BASHPID are equal. $PPID is the process that started the script, here the shell that ran bash 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 -c starts a new shell, not a subshell, so it has its own $$, and its $PPID is 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:

TaskCommandLesson
Wait for the job and get its statuswait "$pid"138
Check whether the process still existskill -0 "$pid"140
Stop itkill "$pid"140
Show information about itps -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:

  1. The process may have ended, leaving a stale PID file.
  2. 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

  • start launches the ticker with nohup (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 of svc.sh itself, which ends a moment later; the ticker keeps running.
  • read_pid accepts the PID file only if it contains a number, kill -0 confirms that such a process exists, and ps -o args= shows that the process is still running ticker.sh. The last check protects against PID reuse.
  • status exits 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.
  • stop sends SIGTERM and then polls with kill -0 every 0.1 seconds, for up to 5 seconds, until the process is gone. A script cannot wait here, because the ticker is not a child of this run of svc.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.pidWhy it is rejected
1process 1 exists, but its command line does not contain ticker.sh
999999no such process (kill -0 fails)
abcnot a number
PID of a ticker ended with kill -9the 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Capturing Process IDs with $! and $$ and get answers drawn from it.

Signed-in readers only.