Introduction
Special variables help you get information about your script and its inputs easily.
$0, $1, $#, $@, $?, $$
echo "Script name: $0" echo "First argument: $1" echo "Number of arguments: $#"
echo "All arguments: $@"ls /notexist
echo "Last command exit status: $?"echo "My process ID is $$"#!/bin/bash # Show script name echo "Script name: $0" # Show all arguments echo "Arguments: $@" # Show number of arguments echo "Number of arguments: $#" # Show first argument echo "First argument: $1" # Run a command ls /tmp # Show exit status of last command echo "Exit status of ls: $?" # Show process ID echo "Process ID: $$"
$# represent?$#$# in bash holds the count of all arguments passed to the script.$0 is the script name, $$ is the process ID, and $? is the last command's exit status, so they don't represent argument count.$# = argument count [OK]$1 holds the first argument passed to the script.$0 is the script name, $# is the argument count, and $$ is the script's process ID, so they are incorrect for printing the first argument../myscript.sh apple banana with this content:echo "$0" echo "$1" echo "$#" echo "$@" echo "$$"
echo "$#"?$# prints$# prints the number of arguments, which is 2 here.echo "Last command status: $?" ls /nonexistent
Last command status: 0 even if the directory doesn't exist. What is the problem?$? holds the exit status of the last command executed before it.echo runs first, so it shows the status of the command before echo, not ls.echo runs before ls, so $? is from previous command -> Option B$$ holds the current script's process ID.$@ holds all arguments passed to the script as separate words.Pass the test and this pattern moves unknown