Reputation: 533
I have a script which asks the user the following question:
read -p "Input time duration of simulation in HH:MM:SS format" -e Time
Now how do I ensure the user entered the correct form for $Time before the variable $Time is actually used?
Upvotes: 1
Views: 1683
Reputation: 8398
I assume you need to check hour < 24, minutes < 60, seconds < 60?
read -p "Input time duration of simulation in HH:MM:SS format " -e Time
while :; do
if [[ $Time =~ ^([0-9]{2}):([0-9]{2}):([0-9]{2})$ ]]; then
if (( BASH_REMATCH[3] < 60 ))\
&& (( BASH_REMATCH[2] < 60 ))\
&& (( BASH_REMATCH[1] < 24 )); then
break
fi
fi
read -p "Wrong format. Please use the HH:MM:SS format " -e Time
done
# Do something with $Time
Upvotes: 2
Reputation: 185025
You can test it like that :
if [[ $Time =~ ^[0-9][0-9]:[0-9][0-9]:[0-9][0-9]$ ]]; then
echo "format is ok"
else
echo >&2 "format is wrong"
fi
Upvotes: 0