Working with Special and Environment Variables
In addition to the variables you create, Bash also provides a set of special and environment variables that serve specific purposes. Understanding these variables can greatly enhance your shell scripting capabilities.
Special Variables
Bash has a number of special variables that hold information about the current shell session or the script being executed. Some commonly used special variables include:
Variable |
Description |
$0 |
The name of the current script or shell |
$1 , $2 , ..., $9 |
The positional arguments passed to the script |
$# |
The number of positional arguments passed to the script |
$? |
The exit status of the most recently executed command |
$$ |
The process ID of the current shell |
Example:
echo "Script name: $0"
echo "First argument: $1"
echo "Number of arguments: $#"
Environment Variables
Environment variables are system-wide variables that can be accessed by all processes running on the system. They are often used to store configuration settings, paths, and other important information.
You can view the current environment variables using the env
command:
env
To set an environment variable, you can use the export
command:
export MY_VARIABLE="LabEx"
You can then access the environment variable in your Bash script:
echo "My variable value: $MY_VARIABLE"
Some commonly used environment variables include:
Variable |
Description |
HOME |
The home directory of the current user |
PATH |
The directories to search for executable files |
SHELL |
The current shell being used |
USER |
The current user's username |
Understanding and working with special and environment variables can greatly enhance the flexibility and functionality of your Bash scripts.
graph TD
A[Special Variables] --> B[$0]
A --> C[$1, $2, ..., $9]
A --> D[$#]
A --> E[$?]
A --> F[$$]
G[Environment Variables] --> H[Viewing Environment Variables]
G --> I[Setting Environment Variables]
G --> J[Commonly Used Environment Variables]