Variables
Hard-coding values makes scripts inflexible. Variables make them dynamic.
Creating Variables
No Spaces Around =
name="John" โ
name = "John" โ (bash thinks "name" is a command)
Using Variables
Prefix with $ to access the value:
Curly Braces
Use ${} when the variable name could be ambiguous:
Always safe to use ${var} instead of $var.
Quoting Matters
Always Quote Variables
"$variable" handles spaces and special characters safely. Unquoted variables cause bugs.
Command Substitution
Store command output in a variable:
$(command) runs the command and captures output.
Environment Variables
System-provided variables:
| Variable | Contains |
|---|---|
$HOME | Home directory |
$USER | Current username |
$PATH | Executable search paths |
$PWD | Current directory |
$SHELL | Default shell |
$RANDOM | Random number |
Export Variables
Make variables available to child processes:
Read-Only Variables
Protect variables from being changed:
Practical Script
#!/bin/bash
# Deployment script with variables
APP_NAME="myapp"
VERSION="1.2.3"
DEPLOY_DIR="/var/www/${APP_NAME}"
BACKUP_DIR="/var/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
echo "Deploying $APP_NAME version $VERSION"
echo "Target: $DEPLOY_DIR"
echo "Backup: $BACKUP_DIR/${APP_NAME}_$TIMESTAMP"
# Create backup
cp -r "$DEPLOY_DIR" "$BACKUP_DIR/${APP_NAME}_$TIMESTAMP"
echo "Deployment complete!"
What is wrong with this code: name = John
Quick Reference
| Syntax | Purpose |
|---|---|
var="value" | Create variable |
$var | Use variable |
${var} | Use (safer syntax) |
"$var" | Use with quoting |
$(command) | Command substitution |
export var | Make available to child processes |
readonly var | Prevent changes |
Key Takeaways
- No spaces around
=when assigning - Use
$varor${var}to access values - Always quote variables:
"$var" $(command)captures command output- Environment variables like
$HOMEare preset exportshares variables with subprocesses
Next: getting input from users.