0
0
Bash Scriptingscripting~5 mins

Default values for input in Bash Scripting

Choose your learning style9 modes available
Introduction
Sometimes users don't enter anything when asked for input. Default values help keep the script running smoothly by using a preset answer.
When asking a user for their name but want to use 'Guest' if they don't type anything.
When asking for a file name but want to use 'output.txt' if no name is given.
When asking for a number but want to use 10 if the user presses enter without typing.
When running a script that needs a value but you want to avoid stopping for missing input.
Syntax
Bash Scripting
read -p "Enter value (default is default_value): " input_variable
input_variable=${input_variable:-default_value}
The read command asks the user for input and stores it in a variable.
The syntax ${variable:-default} means: use the variable's value if set and not null; otherwise, use the default.
Examples
If the user presses enter without typing a name, the script uses 'Guest' as the name.
Bash Scripting
read -p "Enter your name: " name
name=${name:-Guest}
echo "Hello, $name!"
If no file name is entered, 'output.txt' is used as the default.
Bash Scripting
read -p "Enter file name: " file
file=${file:-output.txt}
echo "Saving to $file"
If the user does not enter a number, 10 is used by default.
Bash Scripting
read -p "Enter number: " num
num=${num:-10}
echo "Number is $num"
Sample Program
This script asks for your favorite color. If you just press enter, it will say your favorite color is blue.
Bash Scripting
#!/bin/bash
read -p "Enter your favorite color (default is blue): " color
color=${color:-blue}
echo "Your favorite color is $color."
OutputSuccess
Important Notes
Make sure to use quotes around the prompt text in read to handle spaces properly.
The default value only applies if the user input is empty, not if they type spaces.
This method works well for simple scripts that need quick input with fallback.
Summary
Default values keep scripts running smoothly when users skip input.
Use ${variable:-default} to set a default if input is empty.
Combine read with default values for friendly user prompts.