Skip to the workspace
Pebellslearn by building
Variables and Data  ›  Lesson

Variables: Create, Read, Change

Create, Print, Modify 12 minA Bash variable is created with name=value and no spaces around the equals sign, and its value is read by writing a dollar sign before the name.

shell bash / Variables: Create, Read, Change

Explore each scene at your own pace.

01 · The rule

The rule

Variables: Create, Read, Change

A Bash variable is created with name=value and no spaces around the equals sign, and its value is read by writing a dollar sign before the name.

Assign and expand values while keeping spaces out of assignment syntax.

backup.sh has ~/notes and ~/backups written out in several places. To back up a different folder you would have to edit every line and hope you caught them all. A variable names a value once and lets every line refer to it.

The rule

Assign with no spaces; read with a dollar sign.

Create. name=value, with nothing either side of =. Names use letters, digits and underscores, and cannot start with a digit. By habit, your own variables are lowercase; UPPERCASE names are used for environment variables such as HOME and PATH.

Read. Put $ in front: $src. Wrap the name in braces, ${src}, when the next character could be part of a name.

Change. Assign again to replace; use += to append; unset removes the variable.

#!/usr/bin/env bash
# backup.sh: pack a folder into ~/backups
src="$HOME/notes"
dest="$HOME/backups"
name="notes"
archive="$dest/${name}_backup.tar.gz"

mkdir -p "$dest"
tar -czf "$archive" "$src"
echo "Saved $archive"

Now changing src and name is enough to back up anything. Two quiet facts matter:

  • Bash stores every value as text. count=3 stores the character 3; arithmetic comes later.
  • Reading a variable that was never set is not an error. It expands to an empty string, silently.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.