Reputation: 55
I am working on following script which throws an error if the year is not in digits with exact 4 digits.
so far, I have below code but the only problem is it accepting more digits than 4 which I want to limit it to 4 digits only.
#!/bin/bash
read -p "Enter year " y
while [[ -z $y || $y =~ [A-Za-z]+ || ! $y =~ [0-9]{4} ]]; do
read -p "Enter the year in a valid format [yyyy] " y
done
echo "Selected year is: $y"
output -
Enter the year in a valid format [yyyy] vrgege
Enter the year in a valid format [yyyy] vegter
Enter the year in a valid format [yyyy] 123
Enter the year in a valid format [yyyy] 12345
Selected year is: 12345
It not accepting less than 4 digits but it accepting more than 4 digits.
Can anyone suggest, how to put a condition to get exact only 4 digits?
Upvotes: 0
Views: 75
Reputation: 72732
Without bashisms, for portability, I suggest
case $y in
([0-9][0-9][0-9][0-9])
printf "A four digit year, OK\n"
;;
([0-9][0-9][0-9])
printf "A three digit year, OK\n"
;;
([0-9][0-9])
printf "A two digit year, OK\n"
;;
([0-9])
printf "A one digit year, OK\n"
;;
(*)
printf "NOT OK\n"
esac
You can also combine these with (...|...|...|...)
if you wish.
Upvotes: 0
Reputation: 88889
Replace
[0-9]{4}
by
^[0-9]{4}$
to match only exact four numbers.
See: The Stack Overflow Regular Expressions FAQ
Upvotes: 3