Special Parameters: $#, $?, $$, $!, $@, and $*

Su Suriya Ravichandran Updated 06 Dec 2026
8 min read ·Lesson 43 of 205

Bash keeps a small group of variables that it sets and maintains for you. They have punctuation instead of letters in their names, which is why they are called special parameters. You can read them, but you cannot assign to them. This lesson covers six of the most useful ones.

ParameterMeaning
$#The number of positional parameters (arguments)
$?The exit status of the last foreground command
$$The process ID (PID) of the current shell
$!The process ID of the most recent background command
$@All positional parameters, each as a separate word when quoted
$*All positional parameters, joined into one word when quoted

$# : The Number of Arguments

$# holds the count of arguments given to the script (or to the current function). It does not count $0.

cat > c1.sh <<'EOF'
echo "arguments: $#"
EOF
bash c1.sh
bash c1.sh a b c
bash c1.sh "a b c"
bash c1.sh ""
arguments: 0
arguments: 3
arguments: 1
arguments: 1

Quoting decides how many arguments there are. "a b c" is one argument, and an empty quoted string "" is also one argument. $# is commonly used in conditions such as [[ $# -eq 0 ]] to detect a missing argument, as in the previous lesson.

$? : The Exit Status of the Last Command

Every command finishes with a number called its exit status. By convention 0 means success, and any other number means failure. Bash stores the status of the most recent foreground command in $?:

cat > c2.sh <<'EOF'
true;  echo "after true: $?"
false; echo "after false: $?"
ls /nonexistent_dir 2>/dev/null; echo "after failed ls: $?"
echo "x" > /dev/null; echo "after echo: $?"
grep -q root /etc/passwd; echo "grep found: $?"
grep -q zzzznotthere /etc/passwd; echo "grep missing: $?"
nosuchcommand_xyz 2>/dev/null; echo "unknown command: $?"
EOF
bash c2.sh
after true: 0
after false: 1
after failed ls: 2
after echo: 0
grep found: 0
grep missing: 1
unknown command: 127

Different programs use different failure numbers, which their documentation explains. Some conventions are widely shared: 1 for a general error, 2 for wrong usage (GNU ls returned 2 for a missing directory), 127 for "command not found", and 128 plus a signal number when a program is killed by a signal.

$? Changes After Every Command

Reading $? is itself a command (echo), which succeeds and replaces the previous value:

cat > c2b.sh <<'EOF'
false
echo "first: $?"
echo "second: $?"
EOF
bash c2b.sh
first: 1
second: 0

The first echo showed the status of false. The second echo showed the status of the first echo, which succeeded. If you need the status later, copy it into a variable right away:

cat > c3.sh <<'EOF'
grep -q zzzznotthere /etc/passwd
status=$?
echo "grep status saved: $status"
if [[ $status -ne 0 ]]; then echo "not found"; fi
EOF
bash c3.sh
grep status saved: 1
not found

Functions and $?

A function's exit status is the status of its last command, or the number given to return:

cat > ret.sh <<'EOF'
check() { return 4; }
check
echo "function status: $?"
EOF
bash ret.sh
function status: 4

Lessons 116 and 117 discuss exit codes and the safe use of $? in detail.

$$ : The Process ID of the Shell

Every running program has a unique number called its process ID (PID). $$ expands to the PID of the shell that is running your script. Because the number is different for every run, it is often used to build unique file names:

cat > pid.sh <<'EOF'
echo "PID of this script: $$"
tmp=/tmp/report.$$
echo "temporary file name: $tmp"
EOF
bash pid.sh
PID of this script: 4821
temporary file name: /tmp/report.4821

The number 4821 is only a sample; you will see a different value each time. Run the script twice and the temporary names will differ, so two runs at the same time do not collide on the same file.

There is one special rule. A subshell, written with parentheses, is a separate process, but $$ keeps showing the PID of the original shell. To get the PID of the subshell itself, Bash provides $BASHPID:

cat > c4.sh <<'EOF'
PARENT=$$
( [[ $$ == $PARENT ]] && echo "subshell \$\$ is the same as the parent: yes" )
( [[ $BASHPID != $PARENT ]] && echo "subshell \$BASHPID differs from the parent: yes" )
EOF
bash c4.sh
subshell $$ is the same as the parent: yes
subshell $BASHPID differs from the parent: yes

Lesson 139 uses $$ together with $! for process management.

$! : The PID of the Last Background Command

A command followed by & runs in the background, and the shell continues without waiting for it (lesson 136 covers this fully). Right after starting such a command, $! holds its PID, which lets you wait for it or stop it:

cat > bg.sh <<'EOF'
sleep 30 &
pid=$!
echo "started a background job"
kill "$pid"
wait "$pid" 2>/dev/null
echo "wait status after kill: $?"
EOF
bash bg.sh
started a background job
wait status after kill: 143

The script started sleep 30 in the background, saved its PID, stopped it with kill, and then used wait to collect its result. The status 143 is 128 + 15, where 15 is the number of the termination signal that kill sends by default.

Two details are worth remembering:

  • $! always refers to the most recent background command. Starting a second one replaces the value, so copy it into a variable at once if you need it later.
  • Before any background command has been started, $! is empty.

$@ and $* : All the Arguments

Both parameters stand for the complete list of positional parameters, and the difference appears only when they are quoted. The helper below prints how many items a command receives and what each item contains:

cat > c7.sh <<'EOF'
show() { echo "$# items:"; for x in "$@"; do echo "  [$x]"; done; }
set -- "red apple" "green pear" plum
echo "--- unquoted \$@"; show $@
echo "--- unquoted \$*"; show $*
echo "--- quoted \"\$@\""; show "$@"
echo "--- quoted \"\$*\""; show "$*"
EOF
bash c7.sh
--- unquoted $@
5 items:
  [red]
  [apple]
  [green]
  [pear]
  [plum]
--- unquoted $*
5 items:
  [red]
  [apple]
  [green]
  [pear]
  [plum]
--- quoted "$@"
3 items:
  [red apple]
  [green pear]
  [plum]
--- quoted "$*"
1 items:
  [red apple green pear plum]

The set -- command (explained in lesson 44) simply loads three arguments into the positional parameters so that the example does not need command-line input. The results show three behaviors:

  • Unquoted $@ and $* are identical. Bash splits every argument again on spaces, so red apple turns into two words. This destroys the original argument boundaries.
  • "$@" expands to each argument as its own word, exactly as it was received. red apple stays together.
  • "$*" expands to a single word that joins all arguments with a separator.

The separator for "$*" is the first character of the IFS variable, which is a space by default. Changing IFS turns "$*" into a handy way to join values:

cat > c8.sh <<'EOF'
set -- 2026 11 20
IFS=-
echo "$*"
IFS=,
joined="$*"
echo "joined=$joined"
EOF
bash c8.sh
2026-11-20
joined=2026,11,20

Passing Arguments On

Use "$@" when you want to hand your arguments to another command or function, because it preserves every argument exactly:

cat > c9.sh <<'EOF'
show() { echo "$# items:"; for x in "$@"; do echo "  [$x]"; done; }
wrapper() { show "$@"; }
wrapper "a b" c
wrapper2() { show "$*"; }
wrapper2 "a b" c
EOF
bash c9.sh
2 items:
  [a b]
  [c]
1 items:
  [a b c]

wrapper forwarded two arguments, while wrapper2 squashed them into one. For this reason, "$@" is the correct choice in almost every script, and "$*" is reserved for the cases where you really want one combined string, such as a log message.

When There Are No Arguments

With no arguments, "$@" expands to nothing, but "$*" expands to one empty string:

cat > c10.sh <<'EOF'
show() { echo "$# items"; }
set --
show "$@"
show "$*"
EOF
bash c10.sh
0 items
1 items

Because of this, "$@" can be passed to a command safely even when the list is empty, since the command simply receives no extra arguments.

Using the Parameters Together

A short script can use several special parameters at once. It checks $#, loops over "$@", and ends with a status that other programs can test through $?:

cat > check.sh <<'EOF'
#!/usr/bin/env bash
if [[ $# -eq 0 ]]; then
  echo "No files given" >&2
  exit 2
fi
missing=0
for f in "$@"; do
  [[ -e $f ]] || { echo "missing: $f"; (( missing++ )); }
done
echo "checked $# file(s), $missing missing"
(( missing == 0 ))
EOF
touch real.txt
bash check.sh real.txt ghost.txt
echo "status: $?"
bash check.sh real.txt
echo "status: $?"
missing: ghost.txt
checked 2 file(s), 1 missing
status: 1
checked 1 file(s), 0 missing
status: 0

The last line, (( missing == 0 )), is an arithmetic test whose result becomes the exit status of the script: 0 (success) when nothing is missing and 1 otherwise. Anything that runs the script afterwards can read that status through its own $?.

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 Special Parameters: $#, $?, $$, $!, $@, and $* and get answers drawn from it.

Signed-in readers only.