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:
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.
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.
Final Answer:
read -p "Username: " user
user=${user:-guest}
read -p "Port: " port
port=${port:-8080}
echo "User=$user, Port=$port" -> Option A
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
Master "User Input" in Bash Scripting
9 interactive learning modes - each teaches the same concept differently