0
0
Bash Scriptingscripting~5 mins

Default values for input in Bash Scripting - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Avar=default
B${var:=default}
Cread -p "Enter value: " var
D${var:-default}
What will the following bash code output if the user presses Enter without typing anything? read -p "Name: " name name=${name:-John} echo $name
AJohn
BName
CEmpty line
DError
Which bash parameter expansion assigns the default value to the variable if it is empty or unset?
A${var-default}
B${var:-default}
C${var:=default}
D${var=default}
Why might you want to use default values for input in a bash script?
ATo avoid errors and provide fallback values
BTo make the script slower
CTo ignore user input completely
DTo make the script crash if input is missing
What does this bash code do? read -p "Enter age: " age age=${age:-18} echo "Age is $age"
AAlways prints 'Age is 18'
BPrints the entered age or 18 if empty
CPrints nothing
DCauses an error if no input
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.