Bash Variable Basics
Understanding Bash Variables
Bash variables are fundamental elements in shell scripting that enable data storage, manipulation, and processing. They serve as containers for holding different types of information, from simple strings to complex data structures.
Types of Variables
Bash supports several types of variables:
Variable Type |
Description |
Example |
Local Variables |
Accessible only within the current script |
name="John" |
Environment Variables |
Available system-wide |
PATH=/usr/local/bin |
Special Variables |
Predefined by Bash |
$0 (script name) |
Variable Declaration and Assignment
## Simple variable declaration
username="developer"
## Numeric variable
count=42
## Read-only variable
readonly PROJECT_NAME="MyProject"
## Command substitution
current_date=$(date +%Y-%m-%d)
Variable Naming Conventions
graph TD
A[Variable Naming Rules] --> B[Start with letter or underscore]
A --> C[Contain letters, numbers, underscores]
A --> D[Case-sensitive]
A --> E[No spaces allowed]
Basic Variable Usage Examples
#!/bin/bash
## Basic variable assignment
greeting="Hello, Bash!"
echo $greeting
## Arithmetic operations
number=10
result=$((number + 5))
echo "Result: $result"
## String concatenation
first_name="John"
last_name="Doe"
full_name="$first_name $last_name"
echo "Full Name: $full_name"
Variable Scope and Best Practices
When working with bash variables, understanding scope is crucial. Local variables are confined to the script or function, while environment variables persist across shell sessions.