Obtain the number of positional parameters supplied to a script.
Which special parameter should be used?
$# gives the number of positional parameters; $0 is not included.
Detailed explanation
$?Incorrect. $? is the previous command's exit status.
Incorrect. $? is the previous command's exit status.
$$Incorrect. $$ is the current shell process ID.
Incorrect. $$ is the current shell process ID.
$!Incorrect. $! is the PID of the most recent background command.
Incorrect. $! is the PID of the most recent background command.
$#Correct. $# is the count of positional parameters.
Correct. $# is the count of positional parameters.
Try it yourself
An example you can run in a temporary verification environment.
bash --noprofile --norc -c 'printf "%s\n" "$#"' demo one two threeExpected result
3Key points
- $# counts arguments
- Positional parameters only
- $0 is excluded
Notes
- Environment: GNU Bash 5.2 / 短命シェル
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.