Variable Reference Methods
Basic Variable Referencing
In Bash, there are multiple ways to reference variables, each with unique behaviors and use cases.
Direct Reference
name="LabEx"
echo $name ## Outputs: LabEx
Curly Brace Referencing
## Prevents ambiguity
greeting="Hello, ${name}!"
Advanced Reference Techniques
Default Value Assignment
## Use default if variable is unset or empty
username=${USER:-"guest"}
## Assign default value if variable is unset
path=${HOME:="/home/user"}
Alternative Reference Methods
graph LR
A[Variable Reference] --> B[$var]
A --> C[${var}]
A --> D[${var:-default}]
A --> E[${var:=default}]
Parameter Expansion Methods
Method |
Description |
Example |
${var} |
Basic reference |
name="LabEx"; echo ${name} |
${var:-default} |
Return default if unset |
echo ${unknown:-"Not found"} |
${var:=default} |
Assign default if unset |
username=${USER:="guest"} |
${#var} |
Get variable length |
length=${#name} |
Substring and Manipulation
## Extract substring
text="Hello, LabEx World"
echo ${text:0:5} ## Outputs: Hello
echo ${text:7:5} ## Outputs: LabEx
## Replace substring
file="/path/to/document.txt"
echo ${file/document/report} ## Replaces first occurrence
echo ${file//document/report} ## Replaces all occurrences
Pattern Matching and Trimming
## Remove prefix/suffix
path="/home/user/documents/report.pdf"
echo ${path#*/} ## Removes shortest match from start
echo ${path##*/} ## Removes longest match from start
echo ${path%.*} ## Removes shortest match from end
Best Practices
- Use
${var}
for clear, unambiguous referencing
- Always quote variables to prevent word splitting
- Utilize parameter expansion for complex manipulations
- Be cautious with default value assignments
Understanding these reference methods will enhance your Bash scripting capabilities and help you write more robust and flexible scripts.