Bash Variable Basics
Understanding Variables in Bash
In Bash scripting, variables are fundamental storage units that hold data for later use. They can store different types of information, such as strings, numbers, and arrays.
Variable Naming Conventions
Bash variables follow specific naming rules:
- Start with a letter or underscore
- Contain letters, numbers, and underscores
- Case-sensitive
## Valid variable names
name="LabEx"
_count=10
user_id=1000
## Invalid variable names
2number="invalid"
user-name="not-allowed"
Types of Variables
Local Variables
Local variables are accessible only within the script or function where they are defined.
function example() {
local local_var="I am local"
echo $local_var
}
Environment Variables
Environment variables are available system-wide and can be accessed by all processes.
## Displaying environment variables
echo $HOME
echo $USER
Variable Assignment
Simple Assignment
name="John Doe"
age=30
Command Substitution
current_date=$(date)
file_count=$(ls | wc -l)
Variable Reference
Referencing Variables
greeting="Hello"
echo $greeting ## Outputs: Hello
echo "${greeting}, World!" ## Outputs: Hello, World!
Default Values
## Provide default value if variable is unset
username=${USER:-"anonymous"}
Common Practices
Practice |
Description |
Example |
Quoting |
Prevents word splitting |
name="John Doe" |
Escaping |
Handles special characters |
path="\/home\/user" |
Parameter Expansion |
Advanced variable manipulation |
${variable:-default} |
Best Practices
- Always quote your variables to prevent unexpected behavior
- Use meaningful and descriptive variable names
- Be consistent with naming conventions
By understanding these basics, you'll have a solid foundation for working with variables in Bash scripting, preparing you for more advanced topics like variable exporting.