Skip to content

Variables and $( ): let the shell remember

IntermediateLesson 24 of 667 min

Save values in shell variables, use them with $NAME, see why quotes matter, and put a command’s output into a line with $( ). Practise in your browser.

A variable is a name the shell remembers a value under. Set one with NAME=value and use it with a dollar sign in front:

CITY=Lisbon
echo "I live in $CITY"

No spaces around the =. CITY = Lisbon makes the shell look for a command called CITY.

Quotes

  • In double quotes, $CITY is replaced by its value. Use them around variables, so a value with spaces stays in one piece.
  • In single quotes, nothing is replaced: echo '$CITY' prints $CITY.
  • ${CITY} marks where the name ends: "${CITY}s" gives Lisbons.

Variables the shell sets for you

$HOME is your home folder, $USER your name, $PWD where you are, and $PATH the folders the shell searches for programs:

echo $HOME $USER

A variable you set belongs to this shell only. export NAME hands it to the programs and scripts you start from here too; env lists the exported ones.

A command's output, in the line

$(command) runs the command and puts what it prints right there in the line. It's how you build names and messages from live facts:

date +%F
echo "Today is $(date +%F)"
echo "There are $(ls projects | wc -l) projects"

date +%F prints the date as 2026-01-12, which sorts properly and makes good file names. Old scripts put the command between backquotes for the same thing.

Your turn

Save the path ~/projects/garden-app in a variable called PROJECT and list that folder through the variable. Make a folder inside backups named with today’s date, worked out by date +%F. Then print I have 7 photos, with the number counted by a command.

Next