bashwindows-subsystem-for-linuxerror-checking

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


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


Solution

  • 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.