Variables in Bash
Variables are named containers that store data. Bash variables don't require type declarations โ they're all essentially strings (though Bash can treat them as integers in arithmetic contexts).
Defining Variables
The most important rule: no spaces around the = sign.
# Correct โ no spaces around =
name="Alice"
age=30
greeting="Hello, World"
# WRONG โ spaces cause errors
# name = "Alice" # Error: "name: command not found"Accessing Variables
Use the $ prefix to access a variable's value. Curly braces ${} are optional but recommended for clarity.
name="Alice"
echo "Hello, $name" # Hello, Alice
echo "Hello, ${name}!" # Hello, Alice!
echo "Name has ${#name} chars" # Name has 5 chars
# Curly braces are required when appending text
file="report"
echo "${file}_backup.txt" # report_backup.txt
echo "$file_backup.txt" # WRONG โ looks for $file_backup${variable} with curly braces when the variable name is followed by other characters. It prevents ambiguity.
Environment Variables
Environment variables are system-wide variables available to all processes. Important ones include:
$HOMEโ Your home directory (/home/username)$USERโ Your username$PATHโ Directories where Bash searches for commands$SHELLโ Your default shell$PWDโ Current working directory$EDITORโ Your preferred text editor
# View environment variables
echo $HOME
echo $PATH
# List all environment variables
env
printenv
# Export a variable to make it available to child processes
export MY_VAR="Hello"
# Add to PATH
export PATH="$PATH:/my/custom/bin"Single Quotes vs Double Quotes
This is a crucial distinction in Bash:
- Double quotes (
"): Allow variable expansion and command substitution. - Single quotes (
'): Everything is treated as a literal string. No expansion at all.
name="World"
echo "Hello, $name" # Hello, World (variable expanded)
echo 'Hello, $name' # Hello, $name (literal string)
echo "Today is $(date)" # Today is Mon Jun 21 ...
echo 'Today is $(date)' # Today is $(date)Try It Yourself
Summary
You now understand how to define variables (no spaces around =), access them with $, use environment variables like $HOME and $PATH, export variables, and the critical difference between single and double quotes.