Home > Enterprise >  Is there any way to check if there is any input then contiue?
Is there any way to check if there is any input then contiue?

Time:08-04

I am a newbie in bash programming. I need a bash script which can check if there is an input or not.If there is an input then continue to the second question, otherwise it will not continue unless it forces me to write the input (data). I wrote this script but is not working:

echo "Write buss no:"
        read bussno
        while [ true ] ; do
        
        if [ -z $bussno ] ; then
        
            echo "\Buss No. should be filled"
            read bussno
            
        else    

        echo "Write from date: "
             read startdate
    
        if [ -z $startdate ] ; then
        
            echo "\start date should be filled"
            read startdate
        
        
        fi
        
        
        done

CodePudding user response:

Bash read command support timeout. You can set the timeout to zero:

From man bash:

-t timeout

Cause read to time out and return failure if a complete line of input is not read within timeout seconds. timeout may be a decimal number with a fractional portion following the decimal point. This option is only effective if read is reading input from a terminal, pipe, or other special file; it has no effect when reading from regular files. If timeout is 0, read returns success if input is available on the specified file descriptor, failure otherwise. The exit status is greater than 128 if the timeout is exceeded.

Basically use bussno= ; read -t0 bussno instead of read bussno

CodePudding user response:

There are ways, but you want to keep it simple, yes?
Maybe the logic you want is something like

while [[ -z "$bussno" ]]; do read -r -p "Please enter a business number: " bussno; done
while [[ -z "$startdate" ]]; do read -r -p "Please enter a start date: " startdate; done

This still leaves a lot to be desired in terms of data confirmation, though.
You can add a regex for that if you want, and some follow up confirmations.
For example, for the date,

valid_date='^[[:digit:]]{8}$'
msg="A valid start date is today or later as YYYYMMDD, e.g.: 20220823"
echo "$msg"
until [[ -n "$startdate" && $startdate =~ $valid_date  ]]; do
  read -p "Please enter a valid start date: " startdate
  if date -d "$startdate" >/dev/null 2>&1 &&   # fail if invalid date
     (( "$(date  '%Y%m%d')" <= "$startdate" )) # fail if in past
  then break
  else echo "'$startdate' is not a valid date."
       echo "$msg"
       startdate=                            # reset
  fi
done

These still leave much to be desired, but it's a start.

  • Related