0
0
Bash Scriptingscripting~10 mins

Default values for input in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Default values for input in Bash scripting
📖 Scenario: You are writing a simple Bash script that asks the user for their favorite fruit. Sometimes, the user might not enter anything. You want to make sure the script uses a default fruit if the user leaves the input empty.
🎯 Goal: Build a Bash script that asks for user input and uses a default value if the input is empty.
📋 What You'll Learn
Create a variable to store user input
Set a default value if the input is empty
Print the final chosen fruit
💡 Why This Matters
🌍 Real World
Scripts often ask users for input but need to handle cases where the user presses Enter without typing anything. Using default values keeps scripts friendly and reliable.
💼 Career
Knowing how to handle default values in Bash scripts is useful for system administrators and developers who automate tasks and want to make scripts user-friendly.
Progress0 / 4 steps
1
Create a variable to store user input
Write a line to read user input into a variable called fruit using read -p with the prompt "Enter your favorite fruit: ".
Bash Scripting
Need a hint?

Use read -p "prompt" variable to get input from the user.

2
Set a default value if input is empty
Add a line that sets fruit to "apple" if it is empty, using the syntax ${fruit:-apple}.
Bash Scripting
Need a hint?

Use variable=${variable:-default} to assign a default value if the variable is empty.

3
Print the final chosen fruit
Write a line to print the message "Your favorite fruit is: " followed by the value of fruit.
Bash Scripting
Need a hint?

Use echo to display text and variables.

4
Run the script and see the output
Run the script and enter nothing when prompted. The output should be exactly Your favorite fruit is: apple.
Bash Scripting
Need a hint?

Just press Enter without typing anything when prompted.