In shell scripting, there are several special variables that provide useful information about the script's execution environment. Here are some commonly used special variables:
-
$0: The name of the script itself.echo "Script name: $0" -
$1,$2, ...,$N: Positional parameters that represent the arguments passed to the script.$1is the first argument,$2is the second, and so on.echo "First argument: $1" echo "Second argument: $2" -
$#: The number of positional parameters (arguments) passed to the script.echo "Number of arguments: $#" -
$@: All positional parameters as separate words. It treats each argument as a separate entity.echo "All arguments: $@" -
$*: All positional parameters as a single word. It treats all arguments as a single entity.echo "All arguments (single word): $*" -
$$: The process ID (PID) of the current shell or script. This can be useful for creating unique temporary files.echo "Current process ID: $$" -
$?: The exit status of the last command executed. A value of0typically indicates success, while any non-zero value indicates an error.ls /nonexistentfile echo "Last command exit status: $?" -
$!: The process ID of the last background command executed. This is useful for job control.sleep 10 & echo "PID of last background command: $!" -
$-: The current options set for the shell. This can provide information about the shell's behavior.echo "Current shell options: $-"
These special variables are essential for writing flexible and dynamic shell scripts, allowing you to handle user input, control flow, and manage processes effectively.
