Variables

Bash variables hold text — there's no real distinction between a number and a string until you do arithmetic — and the syntax for setting one is stricter than it looks.

Assigning and reading a variable

Assign with = and no spaces around it; read a variable's value by putting $ in front of its name:

bash greet.sh
#!/bin/bash
name="Maya"
echo "Hello, $name!"
Terminal output
Hello, Maya!
Note: name = "Maya" (with spaces around the =) does not work — Bash reads it as trying to run a command called name with arguments = and "Maya", and fails. The = must touch both the variable name and the value with no spaces.

Command substitution

$(...) runs a command and substitutes its output as a value — the standard way to capture the result of a command into a variable:

bash today.sh
#!/bin/bash
today=$(date +%A)
file_count=$(ls | wc -l)
echo "It's $today, and there are $file_count files here."
Terminal output
It's Tuesday, and there are 12 files here.

Quoting matters

Double quotes let variables expand inside them; single quotes don't expand anything at all — the text is used exactly as written:

bash quoting.sh
#!/bin/bash
city="San Francisco"
echo "I live in $city"
echo 'I live in $city'
Terminal output
I live in San Francisco
I live in $city
The classic gotcha: an unquoted variable gets word-split on spaces before it's used. rm $file where file="my report.txt" tries to delete two separate files, my and report.txt, neither of which exists. Writing rm "$file" instead treats it as one value. As a habit, quote every variable expansion unless you specifically want word-splitting.