Concept Flow - Default values for input
Start
Read input variable
Is input empty?
No→Use input value
Yes
Assign default value
Use value
End
The script reads an input variable, checks if it is empty, assigns a default if needed, then uses the value.
name=${1:-Guest}
echo "Hello, $name!"| Step | Input Parameter $1 | Check if empty | Value assigned to name | Output |
|---|---|---|---|---|
| 1 | "Alice" | No | "Alice" | Hello, Alice! |
| 2 | "" | Yes | "Guest" | Hello, Guest! |
| 3 | Not provided | Yes | "Guest" | Hello, Guest! |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 |
|---|---|---|---|---|
| name | unset | "Alice" | "Guest" | "Guest" |
Syntax: name=${1:-default}
If $1 is empty or unset, assign 'default' to name.
Then use $name safely.
Useful for scripts needing optional inputs.
Prevents empty or unset variables causing issues.${name:-Guest} do in a bash script?variable if it is set and not empty; otherwise, use default.name is set and not empty, it returns name. If name is unset or empty, it returns 'Guest'.name if set; otherwise, it uses 'Guest' as default. -> Option Dname if set; otherwise, it uses 'Guest' as default. [OK]user with a default value 'admin' if input is empty?read command takes input into user. To set a default if empty, use user=${user:-admin}.read -p "Enter your city: " city
city=${city:-Unknown}
echo "City: $city"city is empty string.city=${city:-Unknown} sets city to 'Unknown' because city is empty.read name
name=${name=John}
echo "Name: $name"${name=John} which is invalid for default substitution. The correct syntax is ${name:-John}.read without prompt is valid, name is a valid variable, and echo syntax is correct.${var:-default} which correctly sets default if variable is empty or unset.read -p to prompt user, then sets defaults, then echoes both variables correctly.Pass the test and this pattern moves unknown