0
0
Bash Scriptingscripting~15 mins

Default values (${var:-default}) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Default Values in Bash Scripts with ${var:-default}
📖 Scenario: You are writing a simple bash script to greet users. Sometimes, the user might not provide their name. You want to make sure the script still works by using a default name when none is given.
🎯 Goal: Build a bash script that uses the ${var:-default} syntax to provide a default value for a variable if it is empty or unset.
📋 What You'll Learn
Create a variable called username with no value initially.
Create a variable called default_name with the value Guest.
Use the ${var:-default} syntax to assign a greeting name that uses username if set, or default_name if not.
Print the greeting message using the chosen name.
💡 Why This Matters
🌍 Real World
Scripts often need to handle missing inputs or environment variables. Using default values keeps scripts robust and user-friendly.
💼 Career
Knowing how to use default values in bash is essential for system administrators, DevOps engineers, and anyone automating tasks on Linux or Unix systems.
Progress0 / 4 steps
1
Set up the username variable with no value
Create a variable called username and set it to an empty string.
Bash Scripting
Need a hint?

Use username="" to create an empty string variable.

2
Create a default_name variable with value Guest
Create a variable called default_name and set it to the string Guest.
Bash Scripting
Need a hint?

Use default_name="Guest" to assign the default name.

3
Use ${var:-default} to choose the greeting name
Create a variable called greeting_name that uses ${username:-$default_name} to get username if set, or default_name if username is empty or unset.
Bash Scripting
Need a hint?

Use greeting_name=${username:-$default_name} to assign the value.

4
Print the greeting message with the chosen name
Print the message Hello, <name>! where <name> is the value of greeting_name. Use echo and double quotes.
Bash Scripting
Need a hint?

Use echo "Hello, $greeting_name!" to print the greeting.