I am working on a script, which requests users to enter input.
Ex: read -p "Please enter your email id:" email
I don't want users skipping this entry, this has to be mandatory.I dont want to proceed without input.
I can do a check if variable $email is empty and proceed if not.But, i have around 20 inputs and it is hard to check on all the inputs and if user does not enter variable 19 i don't want to start from 1 again.
If your idea of valid is just "not an empty string", you can loop on the request for each variable sequentially with something like:
while [ -z "$var1" ]
do printf 'Enter variable 1 value: '
read -r var1
[ -z "$var1" ] && echo 'Variable 1 cannot be empty; try again.'
done
while [ -z "$var2" ]
do printf 'Enter variable 2 value: '
read -r var2
[ -z "$var2" ] && echo 'Variable 2 cannot be empty; try again.'
done
...
instead of asking the user to enter all 20 variables and then verifying all of the values and restarting from the beginning if one of them had an error.
#!/bin/bash
#
# Variables
#
# Expand the task list with words that describe the task
declare TASK_LIST="name email"
declare -A ANSWERS
#
# Messages
#
# Use the words from the task-list as string identifier
MSG_STR_NAME="What is your name"
MSG_STR_EMAIL="What is your email"
#
# Action
#
# Work the list
for task in $TASK_LIST
do
# Prepare the message string
str=MSG_STR_${task^^}
# Loop while input is empty
while [ -z "${ANSWERS[$task]}" ]
do
echo ${!str}
read input
ANSWERS[$task]=$input
done
done
#
# Your work to do....
#
echo
echo "Result values are:"
for item in $TASK_LIST
do
echo "$item :: ${ANSWERS[$item]}"
done
Hope this helps
EDIT:
Looks for me like:
0 ~/tmp $ bash aravindadla
What is your name
Simon
What is your email
something
Result values are:
name :: Simon
email :: something
How about another approach in a recent shell (e.g. bash 4 )? Given file
First Name,FNAME
Last Name,LNAME
Birthday,BDAY
and a function declared as
getvar() { while [ ! ${!2} ]; do read -p "$1: " "$2"; done }
this would fill all the variables as requested with minor efforts.
while IFS=, read PR VAR <&3; do getvar "$PR" "$VAR"; echo $VAR"="${!VAR}; done 3< file
First Name: Joe
FNAME=Joe
Last Name: Miller
LNAME=Miller
Birthday: 12.7.88
BDAY=12.7.88
You will need to work out the error checking for each important field.
For example to gather the email address somebody.something@someaddress.extension you will have to check that it has a valid format. Not to forget that once passed it has to be checked for email validity too.
The above example is valid although does not exist but somebody.somethinATsomeaddress.extension is not.
Anything requiring a number only will have to be checked too although this should be staright forward.