0
0
Bash Scriptingscripting~5 mins

Special variables ($0, $1, $#, $@, $?, $) in Bash Scripting

Choose your learning style9 modes available
Introduction
Special variables help you get information about your script and its inputs easily.
When you want to know the name of the script being run.
When you need to access the arguments passed to your script.
When you want to count how many arguments were given.
When you want to check if the last command worked or failed.
When you want to know the process ID of your running script.
Syntax
Bash Scripting
$0, $1, $#, $@, $?, $$
$0 is the script name.
$1 is the first argument, $2 the second, and so on.
$# is the number of arguments.
$@ is all arguments as separate words.
$? is the exit status of the last command (0 means success).
$$ is the process ID of the current script.
Examples
Shows script name, first argument, and how many arguments were passed.
Bash Scripting
echo "Script name: $0"
echo "First argument: $1"
echo "Number of arguments: $#"
Prints all arguments separated by spaces.
Bash Scripting
echo "All arguments: $@"
Runs a command that fails, then shows its exit status.
Bash Scripting
ls /notexist
 echo "Last command exit status: $?"
Prints the current script's process ID.
Bash Scripting
echo "My process ID is $$"
Sample Program
This script prints the script name, all arguments, number of arguments, first argument, runs 'ls /tmp', shows if it succeeded, and prints its own process ID.
Bash Scripting
#!/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: $$"
OutputSuccess
Important Notes
If you run the sample script with: ./script.sh arg1 arg2, $1 is 'arg1' and $# is 2.
Exit status ($?) is 0 if the last command worked, any other number means error.
Process ID ($$) is useful if you want to create temporary files unique to your script.
Summary
Special variables give quick info about your script and its inputs.
$0 is script name, $1 is first argument, $# counts arguments.
$@ holds all arguments, $? shows last command success, $$ is script's process ID.