Bird
0
0

Which script snippet correctly implements this?

hard🚀 Application Q15 of 15
Bash Scripting - User Input
You want to write a script that asks for a username and a port number. If the user presses Enter without input, the username should default to 'guest' and the port to '8080'. Which script snippet correctly implements this?
Aread -p "Username: " user user=${user:-guest} read -p "Port: " port port=${port:-8080} echo "User=$user, Port=$port"
Bread -p "Username: " user user=${user=guest} read -p "Port: " port port=${port=8080} echo "User=$user, Port=$port"
Cread user if [ -z "$user" ]; then user=guest; fi read port if [ -z "$port" ]; then port=8080; fi echo "User=$user, Port=$port"
Dread user user=${user:-guest} read port port=${port-8080} echo "User=$user, Port=$port"
Step-by-Step Solution
Solution:
  1. Step 1: Check default value syntax for both variables

    read -p "Username: " user user=${user:-guest} read -p "Port: " port port=${port:-8080} echo "User=$user, Port=$port" uses ${var:-default} which correctly sets default if variable is empty or unset.
  2. Step 2: Verify prompt usage and output

    read -p "Username: " user user=${user:-guest} read -p "Port: " port port=${port:-8080} echo "User=$user, Port=$port" uses read -p to prompt user, then sets defaults, then echoes both variables correctly.
  3. Final Answer:

    read -p "Username: " user user=${user:-guest} read -p "Port: " port port=${port:-8080} echo "User=$user, Port=$port" -> Option A
  4. Quick Check:

    Use ${var:-default} with read -p for defaults = read -p "Username: " user user=${user:-guest} read -p "Port: " port port=${port:-8080} echo "User=$user, Port=$port" [OK]
Quick Trick: Use read -p with ${var:-default} for clean input with defaults [OK]
Common Mistakes:
MISTAKES
  • Using = instead of :- for defaults
  • Not prompting user with read -p
  • Using ${var-default} which skips empty but not unset

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Bash Scripting Quizzes