Recall & Review
beginner
What is the purpose of using default values for input in bash scripts?
Default values provide a fallback when the user does not enter any input, ensuring the script can continue without errors.
Click to reveal answer
beginner
How do you assign a default value to a variable if the user input is empty in bash?
Use the syntax:
variable=${input:-default_value}. This assigns default_value if input is empty or unset.Click to reveal answer
intermediate
Explain the difference between ${var:-default} and ${var:=default} in bash.
${var:-default} returns default if var is unset or empty but does not change var. ${var:=default} assigns default to var if it is unset or empty.Click to reveal answer
beginner
Write a simple bash script snippet that asks for a username and uses 'guest' as the default if no input is given.
read -p "Enter username: " user
user=${user:-guest}
echo "Hello, $user!"
Click to reveal answer
beginner
Why is it helpful to use default values in scripts that require user input?
It makes scripts more user-friendly and robust by avoiding errors or empty variables when users skip input. It also speeds up usage by providing sensible defaults.
Click to reveal answer
In bash, which syntax assigns a default value to a variable only if it is unset or empty, without changing the variable itself?
✗ Incorrect
The syntax ${var:-default} returns the default if var is unset or empty but does not assign it to var.
What will the following bash code output if the user presses Enter without typing anything?
read -p "Name: " name
name=${name:-John}
echo $name
✗ Incorrect
Since the user input is empty, the default 'John' is assigned and printed.
Which bash parameter expansion assigns the default value to the variable if it is empty or unset?
✗ Incorrect
The := operator assigns the default value to var if it is unset or empty.
Why might you want to use default values for input in a bash script?
✗ Incorrect
Default values help avoid errors and make scripts more user-friendly by providing fallback values.
What does this bash code do?
read -p "Enter age: " age
age=${age:-18}
echo "Age is $age"
✗ Incorrect
If the user enters nothing, age defaults to 18; otherwise, it prints the entered value.
Explain how to use default values for user input in a bash script and why it is useful.
Think about how to assign a value if the user presses Enter without typing.
You got /3 concepts.
Write a bash script snippet that asks for a filename and uses 'default.txt' if the user provides no input.
Use ${variable:-default} syntax after reading input.
You got /3 concepts.