Paulo Bernardo Paulo Bernardo - 4 months ago 20
Linux Question

Bash script. Limit user input

I was able to limit the month and year by using

while :
do
if (( 0 < userAccPDM && userAccPDM <= 12 )); then
accPDM=$userAccPDM && break
else
echo "Try again!" && read -p "Month: " userAccPDM
fi
done


and

while :
do
curYr=$(date +"%Y")
if (( userAccPDY <= curYr )); then
accPDY=$userAccPDY && break
else
echo "Try again!" && read -p "Year: " userAccPDY
fi
done


which means the user cannot put 0 or 13 in Months and put a year in Year greater than the current year.

I was wondering on how I can do that in Day like for example the user typed 2015 in Year and 2 in Month which is February and has only 28 days. If user put 29 in Day, it would be an invalid input. I hope you guys can get what I mean and sorry for the long post.

Answer

You can use date to check if date is valid.

date "+%d/%m/%Y" -d "dd/mm/yyyy" > /dev/null 2>&1
ret=$?

If ret is not 0, then date is valid

Comments