Challenge - 5 Problems
Default Value Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
What is the output of this Bash script using default values?
Consider the following Bash script snippet. What will it print when run without any arguments?
Bash Scripting
name=${1:-"Guest"}
echo "Hello, $name!"Attempts:
2 left
💡 Hint
Look at how the variable 'name' is assigned using ${1:-"Guest"}.
✗ Incorrect
The syntax ${var:-default} means use 'var' if set and not empty; otherwise, use 'default'. Since no argument is passed, $1 is empty, so 'Guest' is used.
💻 Command Output
intermediate2:00remaining
What does this script output when argument is provided?
What will this Bash script print if run with the argument "Alice"?
Bash Scripting
user=${1:-"Unknown"}
echo "User: $user"Attempts:
2 left
💡 Hint
Check how the default value is used only if the argument is missing.
✗ Incorrect
Since the argument "Alice" is provided, $1 is set, so the variable 'user' takes the value 'Alice'.
📝 Syntax
advanced2:00remaining
Which option correctly assigns a default value to a variable if input is empty?
You want to assign the variable 'color' to the first argument or default to 'blue' if the argument is empty or unset. Which option is correct?
Attempts:
2 left
💡 Hint
Remember that :- uses default if variable is unset or empty.
✗ Incorrect
Option D uses ${1:-blue} which means use $1 if set and not empty; otherwise, use 'blue'. Option D uses - which only substitutes if unset, not empty. Option D assigns 'blue' to $1 which is not intended. Option D is invalid syntax.
🔧 Debug
advanced2:00remaining
Why does this script print an empty string instead of the default?
Given this script:
```bash
input=$1
value=${input-"default"}
echo "$value"
```
When run without arguments, it prints an empty line. Why?
Attempts:
2 left
💡 Hint
Check what happens when assigning input=$1 with $1 unset, and note the - operator (no colon).
✗ Incorrect
When run without arguments, $1 is unset. However, `input=$1` assigns an empty string to `input`, so `input` is set but null. The `${input-"default"}` (note: `-` without `:`) uses the value of `input` because it only substitutes if unset, not if empty. Thus, empty is printed.
🚀 Application
expert2:00remaining
How many items are in the array after this script runs?
Consider this Bash script:
```bash
args=(${@:-"default"})
echo ${#args[@]}
```
What number will it print if run without any arguments?
Attempts:
2 left
💡 Hint
Think about how ${@:-"default"} behaves when no arguments are passed; ${@} expands to null.
✗ Incorrect
When no arguments are passed, ${@} expands to null (empty), so ${@:-"default"} expands to "default". Then `args=("default")`, so `${#args[@]}` is 1.