Introduction
Sometimes users don't enter anything when asked for input. Default values help keep the script running smoothly by using a preset answer.
read -p "Enter value (default is default_value): " input_variable
input_variable=${input_variable:-default_value}read -p "Enter your name: " name name=${name:-Guest} echo "Hello, $name!"
read -p "Enter file name: " file file=${file:-output.txt} echo "Saving to $file"
read -p "Enter number: " num num=${num:-10} echo "Number is $num"
#!/bin/bash read -p "Enter your favorite color (default is blue): " color color=${color:-blue} echo "Your favorite color is $color."
${name:-Guest} do in a bash script?variable if it is set and not empty; otherwise, use default.name is set and not empty, it returns name. If name is unset or empty, it returns 'Guest'.name if set; otherwise, it uses 'Guest' as default. -> Option Dname if set; otherwise, it uses 'Guest' as default. [OK]user with a default value 'admin' if input is empty?read command takes input into user. To set a default if empty, use user=${user:-admin}.read -p "Enter your city: " city
city=${city:-Unknown}
echo "City: $city"city is empty string.city=${city:-Unknown} sets city to 'Unknown' because city is empty.read name
name=${name=John}
echo "Name: $name"${name=John} which is invalid for default substitution. The correct syntax is ${name:-John}.read without prompt is valid, name is a valid variable, and echo syntax is correct.${var:-default} which correctly sets default if variable is empty or unset.read -p to prompt user, then sets defaults, then echoes both variables correctly.Pass the test and this pattern moves unknown