[bash] how is proper way to validate user input

hi all,

i have a script that need user input provide all variables that needed to complete a job.

this is my current script:

    echo "type file source and it full path [e.g: /srv/src/source.csv or "/srv/src dir/my source.csv"]:"
    read INPUTFILE
    if [ -z $INPUTFILE ] || [ ! -f $INPUTFILE ];
    then
     echo "ERROR: you didn't enter a file source or file source is not exist."
     exit 1
    fi
 
    echo "enter directory for output file [e.g: /home/admin/dst/]:"
    read OUTPUTFILE
    if [ ! -d "$OUTPUTFILE ] ;
    then
     echo "ERROR: directory is no exist."
     exit 1    
    fi

    echo "enter number of header lines of $INPUTFILE :"
    read HEADERLINE
    if [ -z $HEADERLINE ];
    then
     echo "ERROR: please enter number of header line."
     exit 1
    fi
    
    tail -n +`expr $HEADERLINE + 1` $INPUTFILE > /tmp/trim0.tmp
    <next command>
    <next command>
    <next command>
    printf "%s\n" "$outputdir/summary.csv is created"

as you can see if the user fail to input the correct variable, script will exit and user should run it again and start the process from begining.

my question: what is the proper way to ask user to enter the correct variable if put wrong variable or he press enter before he provide any input?

e.g:

type file source and it full path [e.g: /srv/src/source.csv or "/srv/src dir/my source.csv"]:
<user only press enter>
ERROR: you didn't enter a file source or file source is not exist."
type file source and it full path [e.g: /srv/src/source.csv or "/srv/src dir/my source.csv"]:
/srv/src/source.csv

enter directory for output file [e.g: /home/admin/dst/]: 
/home/admin/dst/

enter number of header lines of $INPUTFILE :
<user only press enter>
ERROR: please enter number of header line.
enter number of header lines of $INPUTFILE :
3

/home/admin/dst/summary.csv is created

use a while loop.

while true
do
   echo "enter directory for output file [e.g: /home/admin/dst/]:"
    read OUTPUTFILE
    if [ ! -d $OUTPUTFILE ]  ;
    then
         echo "ERROR: invalid directory"
     else
         echo "Directory validated successfully.."
         break
     fi
done

hope this helps

1 Like

oic....

thank you for your help Arun_Linux :slight_smile:

:: update ::
correction for my own script:
1.

 echo "type file source and it full path [e.g: /srv/src/source.csv or "/srv/src dir/my source.csv"]:"

should change to

 echo "type file source and it full path [e.g: /srv/src/source.csv or /srv/src dir/my\ source.csv]:"
if [ -z $INPUTFILE ] || [ ! -f $INPUTFILE ];

should change to

if [ -z "${INPUTFILE}" ] || [ ! -f "${INPUTFILE}" ];

those will help me to handle source filename that contain space.