0
0
Bash Scriptingscripting~5 mins

Default values (${var:-default}) in Bash Scripting

Choose your learning style9 modes available
Introduction
This helps you use a default value when a variable is empty or not set, so your script keeps working smoothly.
You want to use a default file name if the user does not provide one.
You want to set a default greeting if no name is given.
You want to avoid errors when a variable might be empty.
You want to make your script more flexible with optional inputs.
Syntax
Bash Scripting
${variable:-default_value}
If 'variable' is unset or null, 'default_value' is used instead.
This does not change the variable's value, it only provides a fallback.
Examples
Prints the value of 'name' if set; otherwise prints 'Guest'.
Bash Scripting
echo "${name:-Guest}"
Assigns 'file' to 'filename' if set; otherwise assigns 'default.txt'. Then prints it.
Bash Scripting
filename=${file:-default.txt}
echo "$filename"
Greets the user by name if set; otherwise uses 'friend'.
Bash Scripting
echo "Welcome, ${user:-friend}!"
Sample Program
This script shows how to use a default value 'blue' when the variable 'color' is not set.
Bash Scripting
#!/bin/bash

# Variable 'color' is not set

# Use default value 'blue' if 'color' is unset or null
chosen_color=${color:-blue}
echo "The chosen color is $chosen_color"
OutputSuccess
Important Notes
This syntax only uses the default value temporarily; it does not assign it to the variable.
If you want to assign the default value to the variable when it is empty, use ${var:=default} instead.
Summary
Use ${var:-default} to safely use a default when a variable is empty or missing.
It helps avoid errors and makes scripts more user-friendly.
It does not change the original variable's value.