Reputation: 57
From a shell script, I want to ask the user to input data such as database name, database user etc.
When the user inadvertently presses the enter key, the input is blank. How do I make the input required? If the input is blank, the script asks that question again?
My current script, but maybe it doesn't work as I expected.
#!/bin/bash
# Clear terminal first
clear
echo -n "Your Database Name : "
read dbname
if [ "$dbname" = "" ]; then
echo "ANSWER CANNOT BE BLANK!"
echo -n "Your Database Name : "
read dbname
else
... another code here
But this does not rule out the possibility that the user does not accidentally (or even perhaps on purpose) hit the enter key – how many if else condition do I have to make?
Upvotes: 1
Views: 1194
Reputation: 21502
Use a loop:
#!/bin/bash -
clear
echo -n "Your Database Name: "
while read dbname; do
test "$dbname" != "" && break
echo "ANSWER CANNOT BE BLANK!"
echo -n "Your Database Name : "
done
echo "dbname = $dbname"
Edit: fix for Ctrl-D
The above-mentioned code leaves an empty string, if the user enters Ctrl-D
. The following version handles this case:
#!/bin/bash -
clear
until read -r -p "Your Database Name: " db && test "$db" != ""; do
continue
done
echo "db='$db'"
Note, we use the Bash builtin read
command. If the user enters Ctrl-D
(manual end-of-file), the read
command exits with non-zero status, which is interpreted as error. See info bash 'read'
.
This version will also work in non-interactive mode:
echo -e "\n name \n" | ./script.sh
Upvotes: 0
Reputation: 15471
You may use an infinite loop and break
if input is not empty:
while true; do
echo -n "Your Database Name: "
read dbname
if [[ "$dbname" != "" ]]
then
echo "dbname = $dbname"
break
fi
done
Upvotes: 4