Here are the 4 main methods I use to handle user input in a Bash script (each with its own purpose):
echo -e "Enter the site URL:" read SITE_URL
The value entered by the user will be available as the
Since this is an optional input the user can simply skip it without typing any value.
So you might want to check if there is a value:
if [ "$SITE_URL" ] then # There is a value. else # No value. fi
The following method makes
SITE_URL a required input:
SITE_URL=; until [[ $SITE_URL ]]; do echo -e "Enter the site URL:" read SITE_URL done;
The user will not be able to continue until a value is entered.
The input will simply reappear if the user tries to continue without entering a value.
Input with restricted values
In some cases, we would like to limit the possible values that the user can enter.
This is especially common in yes and no questions.
The following code accepts an input of
while true; do read -n 1 -p "Do you want to proceed? (y/n) " yn case $yn in [Yy]* ) echo; echo; echo "Proceeding..."; echo; break;; [Nn]* ) echo; echo; echo "Exiting..."; exit;; * ) echo; echo "Please answer yes (y) or no (n)."; echo;; esac done
In the example above, if the user enters
y, the loop will break and the script will continue.
If the user enters
n, the script will be stopped completely and the rest of the script will not be executed (
-n 1 attribute (after the
read command) will cause the script to continue automatically after entering one character.
We can change this (for example, to
-n 2 to continue automatically after 2 characters).
Alternatively, we can remove it completely (which will force the user to press the Enter key to continue).
Input to continue execution
Sometimes we want to pause the execution of the Bash script and wait for the user to confirm.
As soon as the user presses any key, the script will continue.
This can be done as follows:
read -n 1 -s -r -p "Press any key to continue " echo; echo; echo "Proceeding..."; echo