Variables: Create, Read, Change
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.
The shortcut
Left of =, a bare name. Everywhere else, a dollar sign. Then glance at the character after the name: if it is a letter, digit or underscore, add braces.
Find each expansion
Two:
$dest, then${name}. Everything else is literal text.
The most common beginner error is src = "$HOME/notes". Bash splits the line on spaces and tries to run a command named src with the arguments = and the path, so you get src: command not found.
Drills
Answer fast — trust the rule.
Which line correctly stores 3 in count?
After name=notes, what does echo "$name_old" print?
How do you print notes_old from name=notes?
What does n=hi; n+=" there"; echo "$n" print?
What happens when a script runs src = /tmp?
Remember
- Assign with no spaces; read with a dollar sign.
- Add braces when a letter, digit or underscore follows the name:
${name}_old. - Trap: an unset or misspelled variable is silently empty, not an error.
