Concept Flow - Default values (${var:-default})
Start
Check if var is set and not empty
Use var value
Output
End
The script checks if a variable is set and not empty; if yes, it uses its value, otherwise it uses the default value.
name="" echo "Hello, ${name:-Guest}!" name="Alice" echo "Hello, ${name:-Guest}!"
| Step | Variable 'name' | Condition '${name:-Guest}' | Output |
|---|---|---|---|
| 1 | '' (empty string) | Empty or unset, use default 'Guest' | Hello, Guest! |
| 2 | 'Alice' | Set and not empty, use 'Alice' | Hello, Alice! |
| Variable | Start | After Step 1 | After Step 2 |
|---|---|---|---|
| name | unset | '' (empty string) | 'Alice' |
Syntax: ${var:-default}
If 'var' is unset or empty, use 'default'.
Otherwise, use 'var' value.
Common in scripts to provide fallback values.
Example: echo "${name:-Guest}" prints 'Guest' if name is empty or unset.${var:-default} do in a bash script?${var:-default}var if it is set and not empty; otherwise, use default.var is changedvar, it only provides a fallback value for use.var if set; otherwise, it uses default without changing var. -> Option Avar is empty or unset [OK]name or use "Guest" if name is empty or unset?${var:-default} prints var if set; otherwise, prints default.Guest only if name is set. echo ${name?Guest} throws error if name is unset. Only echo ${name:-Guest} prints name or "Guest" safely.unset user
user=""
echo "User: ${user:-anonymous}"user is first unset, then set to an empty string.user is empty (empty string counts as unset for :-), the expression uses the default "anonymous".echo "Name: ${name-default}"${name-default} uses default only if name is unset, but not if empty.${name:-default} is needed.path if set and not empty, otherwise print "/usr/local/bin". But if path is set to an empty string, you want to treat it as unset. Which command correctly does this?path if it is set and not empty; otherwise, print the default "/usr/local/bin".${path:-default} uses default if path is unset or empty. ${path-default} only uses default if unset, not empty. ${path:=default} assigns default to path. ${path:+default} prints default only if path is set.Pass the test and this pattern moves unknown