Persistent vs. Temporary
${var:=default} — The Persistent Assignment
Logic: If $var is empty or unset, set $var to default and then return that value.
Example:
ubuntu in 🌐 cato in ~
❯ echo $name
ubuntu in 🌐 cato in ~
❯ echo "${name:=User}"
User
ubuntu in 🌐 cato in ~
❯ echo $name
User
- name="" (name is empty)
- echo “${name:=User}”
- Bash sees name is empty.
- It assigns “User” to the variable name
- It then prints “User”.
- echo $name now prints “User” because the variable was actually changed.Bash
Note: The = stands for equal, as in “Make the variable equal to this from now on.
${var:-default} — The Temporary Fallback
Logic: If $var is empty or unset, use default just for this command, but do not change the original variable.
Example:
ubuntu in 🌐 cato in ~
❯ name=""
ubuntu in 🌐 cato in ~
❯ echo "Hello, ${name:-User}"
Hello, User
ubuntu in 🌐 cato in ~
❯ echo $name
- name=”" (name is empty)
- echo “Hello, ${name:-User}”
- Bash sees name is empty.
- It provides “User” to the echo command.
- It does not touch the variable name.
- echo $name returns nothing (empty) because the expansion was “read-only.”
Note: The - is like a dash in and out. It provides the value and leaves.
The Patterns
| Syntax | Meaning |
|---|---|
${var:-default} |
Use default if var is empty/unset (var unchanged) |
${var:=default} |
Set var to default if empty/unset (var updated) |
${var:?error} |
Exit with error message if var is empty/unset |