Special parameters and shell identity
What you need to know
Special parameters provide information Bash maintains automatically. $? is the last command status; $$ is the process ID of the invoked shell (it remains the invoking shell PID in a parenthesized subshell); $! is the PID of the most recent background job put into the background; $- lists current option flags. BASHPID identifies the current Bash process and can differ from $$ in a subshell. PIDs and option flags depend on the environment. $0, $#, $@ and $* are covered next.
Run each example separately as a new Bash script (Chapter 1). Tested with Bash 5.2.37 on Debian 13, default shell options; no personal configuration is required.
Capture status immediately
falsestatus=$?printf 'saved=%s\n' "$status"printf 'now=%s\n' "$?"Expected stdout:
saved=1now=0Save the status before another command overwrites it. The first printf succeeds, so the next expansion of $? is zero.
Compare shell identifiers
printf 'outer: %s %s\n' "$$" "$BASHPID"( printf 'inner: %s %s\n' "$$" "$BASHPID" )Illustrative output (values vary):
outer: 1234 1234inner: 1234 1235Parentheses run the contained command in a subshell environment. In this test, the two outer numbers match, the inner first number stays the same and the inner second number differs. Actual digits vary. Subshell rules are explained in a later chapter.
Observe a background job and wait
true &job=$!wait "$job"printf 'job status=%s\n' "$?"printf 'flags=%s\n' "$-"Illustrative output (values vary):
job status=0flags=hBThe ampersand starts a background command; wait collects its status. The first line is job status=0; the second shows current option letters, which vary. This bounded example completes immediately; job control is covered later.
Common mistakes
$$ is not a reliable identifier of the current Bash process inside every subshell. Use BASHPID when you specifically need that process ID, and never assume a particular numeric PID.
Practice
Save the result of false in a variable, run true, then print the saved value and explain why it still represents the earlier command.
Next lesson: Positional parameters and shift