Shell Variables Basics
Introduction to Shell Variables
In Linux shell programming, variables are fundamental storage units that allow you to store and manipulate data. They serve as containers for holding different types of information, such as strings, numbers, and arrays.
Types of Shell Variables
1. Local Variables
Local variables are specific to the current shell session and are not accessible by child processes.
name="LabEx"
age=25
2. Environment Variables
Environment variables are global and can be accessed by the current shell and its child processes.
export PATH="/usr/local/bin:$PATH"
export USER=$(whoami)
Variable Naming Conventions
Rule |
Example |
Description |
Start with letter or underscore |
_valid_name , username |
Valid variable names |
Case-sensitive |
Name vs name |
Different variables |
No spaces around = |
name="LabEx" |
Correct assignment |
Variable Declaration and Assignment
## Simple assignment
greeting="Hello, World!"
## Numeric variables
counter=10
## Read-only variables
readonly PI=3.14159
## Null/empty variable
empty_var=""
Variable Expansion
graph LR
A[Variable Name] --> B{Expansion Method}
B --> |${var}| C[Full Expansion]
B --> |$var| D[Simple Expansion]
B --> |"${var:-default}"| E[Default Value]
Best Practices
- Use descriptive variable names
- Quote variables to prevent word splitting
- Use
readonly
for constant values
- Be mindful of variable scoping
By understanding these basics, you'll be well-equipped to work with shell variables in Linux environments.