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=3stores the character3; arithmetic comes later. - Reading a variable that was never set is not an error. It expands to an empty string, silently.