Making and using variables
A variable gives a name to a piece of text. Set it with name=value and no spaces around the =. Read it back by putting $ in front:
ship="Black Pearl"
echo "$ship"
echo "The $ship sails at dawn"In the terminal
student@vulntech:~$ ship="Black Pearl" student@vulntech:~$ echo "$ship" Black Pearl student@vulntech:~$ echo "The $ship sails at dawn" The Black Pearl sails at dawn
Common mistake: Spaces break an assignment.
ship = Pearltries to run a command calledship; it must beship=Pearl, with no spaces.
Curly braces: where the name ends
Use ${name} when the variable is touching other text, so bash knows where the name stops:
word=sail
echo "$words"
echo "${word}s"In the terminal
student@vulntech:~$ word=sail student@vulntech:~$ echo "$words" student@vulntech:~$ echo "${word}s" sails
$words was a different, empty variable, so the first line is blank. ${word}s is sail followed by s.
Capturing output: $( )
From the pipes module: $(command) runs a command and gives you its output, perfect for putting into a variable:
today=$(date +%F)
files=$(ls /etc | wc -l)
echo "On $today, /etc had $files entries"In the terminal
student@vulntech:~$ today=$(date +%F) student@vulntech:~$ files=$(ls /etc | wc -l) student@vulntech:~$ echo "On $today, /etc had $files entries" On 2026-10-17, /etc had 65 entries
Why double quotes matter
Put variables in double quotes. Without them, a value with spaces is split into several words, which causes some of the most common script bugs:
name="Jolly Roger"
touch $name
ls
rm *.txt 2>/dev/null; touch "$name"
lsIn the terminal
student@vulntech:~$ name="Jolly Roger" student@vulntech:~$ touch $name student@vulntech:~$ ls Jolly Roger student@vulntech:~$ rm *.txt 2>/dev/null; touch "$name" student@vulntech:~$ ls Jolly 'Jolly Roger' Roger
Without quotes, touch $name made two files, Jolly and Roger. With quotes, it made the one file you meant.
| Quoting | What bash does with it |
|---|---|
"$name" | Replaces $name with its value, as one word |
'$name' | Leaves it exactly as written: single quotes turn off $ |
$name | Replaces it, then splits the value at spaces (usually not what you want) |
fruit=apple
echo "I like $fruit"
echo 'I like $fruit'In the terminal
student@vulntech:~$ fruit=apple student@vulntech:~$ echo "I like $fruit" I like apple student@vulntech:~$ echo 'I like $fruit' I like $fruit
Remember: Set with
name=value(no spaces), read with"$name". Double quotes keep a value in one piece; single quotes turn off$.