Skip to content
AgileLogics
5 min read

Variables

Prerequisites: Your first script

A variable gives a name to a value so you can use it later.

Real-world analogy: a variable is a labeled box. You put something inside, and later refer to the box by its label.

Syntax

name="Ada"
count=3
echo "$name has $count cats"
Ada has 3 cats
  • Assign with name=value — no spaces around =.
  • Use a variable's value with $name. Wrap it in double quotes — "$name" — for reasons the next lesson explains.
  • Variables hold text. Bash has no separate number type (arithmetic has its own lesson).

Braces

${name} marks exactly where the variable name ends:

fruit="apple"
echo "I have 3 ${fruit}s"
echo "I have 3 $fruits"
I have 3 apples
I have 3

Without braces, Bash looks for a variable called fruits, which doesn't exist — so it prints nothing there. Unset variables silently expand to empty text, a common source of bugs (Level 3 shows how to catch them).

Naming

  • Letters, digits, and underscores; can't start with a digit.
  • Use lowercase for your own variables (backup_dir). UPPERCASE names are conventionally for environment variables (PATH, HOME) — avoid accidentally overwriting them.

Environment variables

Some variables are set for you:

# illustrative
echo "$HOME"
echo "$USER"
echo "$PWD"
/home/ada
ada
/home/ada/projects

export NAME=value makes a variable available to programs you run from the shell — covered in Level 2.

Common mistakes

  • Spaces around =: name = "Ada" runs a command called name with the arguments = and Ada, giving name: command not found.
  • Using $ when assigning: $name="Ada" is wrong. $ is only for reading a value.

Practice

Store a city and a temperature in two variables, then print It is 21 degrees in Oslo.

Show solution
city="Oslo"
temperature=21
echo "It is $temperature degrees in $city"
It is 21 degrees in Oslo