I have the following lines in a bash script:
while true; do
DATE=date
FORMAT="%Y%m%d"
read -p "Enter start date (YYYYMMDD) " STARTDATE
if date=$(date -d "$STARTDATE" +'+%Y%m%d'); then
start_date=`$DATE +$FORMAT -d $STARTDATE`
echo $start_date
break
fi
echo "Please use right format (YYYYMMDD) "
done
This works fine as long as the input are 8 numbers (e.g. it accepts "20210901" and rejects "20213131"). However, when the input is totally off (e.g. "a" or "nonsense"), it simply takes today's date. How could the code be modified for a stricter check of the format?
The modified code reads:
valid=0
while true; do
DATE=date
FORMAT="%Y%m%d"
read -p "Enter start date (YYYYMMDD) " initialdate
if date=$(date -d "$initialdate" +'+%Y%m%d'); then
start_date=`$DATE +$FORMAT -d $initialdate`
if [[ "$start_date" =~ ^[[0123456789]]{8}$ ]]
then
valid=1
echo "valid";
echo $start_date
break
else
echo "Invalid format"
fi
fi
echo "Please use right format (YYYYMMDD) "
done