Beginner โฑ 15 min Lesson 4 of 13

๐Ÿ“ฆ Variables & Environment

Define variables, use environment variables, and understand quoting.

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.

bash
# 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.

bash
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
๐Ÿ’ก Tip: Always use ${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
bash
# 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.
bash
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)
โš ๏ธ Warning: A common beginner mistake is using single quotes when you want variable expansion. If your variables aren't expanding, check your quote types!

Try It Yourself

Terminal

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.

๐Ÿงช Test Your Knowledge

Answer the questions below to check your understanding of this lesson.