Variables — Storing and Managing Data in Bash Scripts¶
Variables are the foundation of every Bash script. A variable stores a value that can be reused throughout a script, making automation flexible, reusable, and easier to maintain. Instead of hardcoding values, scripts use variables to store filenames, user input, command output, configuration values, and system information. Every Linux administrator, DevOps engineer, Cloud Architect, Platform Engineer, and Site Reliability Engineer (SRE) should master variables to write efficient and production-ready Bash scripts.
Learning Path¶
Course Progress
What You'll Learn¶
After completing this lesson, you'll be able to:
- Understand Bash variables
- Create and use variables
- Follow variable naming rules
- Work with environment variables
- Store command output in variables
- Read user input into variables
- Understand variable scope
- Apply variable best practices
Prerequisites¶
Complete:
- Modules 1–9 of Linux Mastery
Why Learn Variables?¶
Imagine writing a backup script.
Without variables:
cp /home/basha/data.txt /backup/
tar -czf /backup/data.tar.gz /backup/
echo "Backup stored in /backup"
If the backup location changes, every occurrence must be updated.
Using variables:
BACKUP_DIR="/backup"
cp /home/basha/data.txt $BACKUP_DIR
tar -czf $BACKUP_DIR/data.tar.gz $BACKUP_DIR
echo "Backup stored in $BACKUP_DIR"
Only one value needs to change.
What is a Variable?¶
A variable is a named container that stores data.
Example:
Whenever the script references USERNAME, Bash substitutes the stored value.
Creating Variables¶
Syntax:
Example:
Display the value.
Output:
Important Syntax Rules¶
Correct:
Incorrect:
Spaces around = are not allowed.
Variable Naming Rules¶
Variable names:
- May contain letters
- May contain numbers
- May contain underscores (
_) - Cannot begin with a number
- Cannot contain spaces
Valid:
Invalid:
Using Variables¶
Reference a variable using $.
Example:
Output:
Using Curly Braces¶
Curly braces improve readability.
Output:
String Variables¶
Output:
Numeric Variables¶
Output:
Arithmetic Operations¶
Use arithmetic expansion.
Output:
Other operations:
Command Substitution¶
Store command output.
Display:
Another example:
Reading User Input¶
Prompt the user.
Environment Variables¶
Environment variables are available to the shell and child processes.
View one variable.
Common environment variables:
| Variable | Description |
|---|---|
HOME | User's home directory |
USER | Current username |
PATH | Executable search path |
PWD | Current working directory |
SHELL | Current shell |
HOSTNAME | System hostname |
View all environment variables.
Export Variables¶
Make a variable available to child processes.
Verify.
Unset Variables¶
Remove a variable.
Quotes in Variables¶
Double quotes allow variable expansion.
Single quotes prevent expansion.
Output:
Common Commands¶
Create variable.
Display variable.
Read input.
Export variable.
Remove variable.
Display environment variables.
Real Production Examples¶
Store backup directory.
Store hostname.
Store current date.
Generate backup filename.
Production Perspective¶
Variables are used extensively in:
- Backup automation
- Deployment scripts
- CI/CD pipelines
- Kubernetes automation
- Infrastructure provisioning
- Monitoring scripts
- Cloud automation
- Configuration management
Well-designed scripts avoid hardcoded values and rely on variables for flexibility.
Hands-on Lab¶
Task 1¶
Create a variable.
Display it.
Task 2¶
Store your username.
Task 3¶
Store today's date.
Task 4¶
Perform arithmetic.
Task 5¶
Read user input.
Task 6¶
Display environment variables.
Task 7¶
Export a variable.
Task 8¶
Remove the variable.
Command Deep Dive¶
| Command | Purpose | Production Example |
|---|---|---|
echo | Display variable value | Debugging |
read | Read user input | Interactive scripts |
export | Export variable | Environment configuration |
unset | Remove variable | Cleanup |
env | Display environment variables | Troubleshooting |
$(command) | Store command output | Dynamic values |
Common Variable Mistakes¶
| Mistake | Solution |
|---|---|
Spaces around = | Remove spaces |
Missing $ | Use $VARIABLE |
| Invalid variable names | Follow naming rules |
| Forgetting quotes | Quote strings containing spaces |
| Hardcoding values | Use variables instead |
Production Troubleshooting Scenario¶
Scenario
A backup script suddenly begins writing backups to the wrong directory.
Investigation:
Output:
The variable was never initialized.
Solution:
The script now writes backups to the correct location.
Best Practices¶
- Use descriptive variable names.
- Follow uppercase naming for constants.
- Quote variables when appropriate.
- Avoid hardcoded values.
- Use command substitution for dynamic values.
- Export variables only when necessary.
Common Mistakes¶
❌ Adding spaces around =.
✅ Avoid this mistake: adding spaces around =.
❌ Forgetting $ when referencing variables.
✅ Remember to $ when referencing variables.
❌ Using invalid variable names.
✅ Avoid using invalid variable names when a safer approach exists.
❌ Hardcoding paths and configuration values.
✅ Avoid this mistake: hardcoding paths and configuration values.
❌ Not quoting variables containing spaces.
✅ Always quoting variables containing spaces.
Interview Questions¶
Beginner¶
- What is a variable?
- How do you create a variable in Bash?
- How do you display a variable?
- What does
$HOMErepresent?
Intermediate¶
- What is command substitution?
- What is the difference between local and environment variables?
- Why is
exportused? - What is the difference between single and double quotes?
Architect Level¶
- How would you design reusable Bash scripts using variables?
- Why should configuration values be stored in variables instead of hardcoded?
- How would you securely manage sensitive values in Bash scripts?
Summary¶
In this lesson, you learned:
- Variables
- Variable naming rules
- Variable expansion
- Environment variables
- Command substitution
- User input
- Arithmetic operations
- Production scripting best practices
Variables are the building blocks of Bash scripting. They make scripts reusable, maintainable, and dynamic by allowing values to be stored, modified, and reused throughout the script. Mastering variables is the first step toward writing professional automation scripts.
Key Takeaways¶
- Variables store reusable data in Bash scripts.
- Variable assignment does not allow spaces around
=. - Use
$to access variable values. - Use
$(command)to capture command output. - Use
exportto make variables available to child processes. - Avoid hardcoding values by using descriptive variables.
What's Next?¶
Conditions — Making Decisions in Bash Scripts
You'll explore:
ifstatementsif-elseandelif- Comparison operators
- File test operators
- String and numeric comparisons
- Logical operators
- Nested conditions
- Production scripting examples
By the end of the lesson, you'll be able to make intelligent decisions in Bash scripts based on user input, file states, command results, and system conditions.