Reputation: 5
I am trying to implement a Bash script that checks whether the number given by the user is single/2-digit/3-digit. I can only use case..esac statement. The following program works fine for single digit but the reset of the cases doesn't execute.
echo -e "\n-----NUMBER CHECK-----"
echo -e -n "\nEnter a number: "
read num
case $num in
[0-9])
echo -e "\nSINGLE DIGIT NUMBER!"
;;
[10-99])
echo -e "\nDOUBLE DIGIT NUMBER!"
;;
[100-999])
echo -e "\nTRIPLE DIGIT NUMBER!"
;;
*)
echo -e "\nInvalid Input!"
;;
esac
Upvotes: 0
Views: 4342
Reputation: 2537
An alternative but hacked solution:
echo -e "\n-----NUMBER CHECK-----"
echo -e -n "\nEnter a number: "
read num
case $num in
*[!0-9]*|????*) good=0 ;;
*) good=1;
esac
case 1 in
$((good == 1 && num <= 9)))
echo -e "\nSINGLE DIGIT NUMBER!"
;;
$((good == 1 && num <= 99)))
echo -e "\nDOUBLE DIGIT NUMBER!"
;;
$((good == 1 && num <= 999)))
echo -e "\nTRIPLE DIGIT NUMBER!"
;;
*)
echo -e "\nInvalid Input!"
;;
esac
Upvotes: 0
Reputation: 7801
Something like this.
#!/usr/bin/env bash
printf '\n-----NUMBER CHECK-----\n\n'
read -rp 'Enter a number: ' num
case $num in
[0-9])
printf '\nSINGLE DIGIT NUMBER!'
;;
[0-9][0-9])
printf '\nDOUBLE DIGIT NUMBER!'
;;
[0-9][0-9][0-9])
printf '\nTRIPLE DIGIT NUMBER!'
;;
*)
printf >&2 '\nINVALID INPUT!'
;;
esac
An alternative is to use a regex pattern matching using the test =~
operator if your version of bash supports it.
#!/usr/bin/env bash
printf '\n-----NUMBER CHECK-----\n\n'
read -rp 'Enter a number: ' num
if [[ $num =~ ^[[:digit:]]{1}$ ]]; then
printf '\nSINGLE DIGIT NUMBER!'
elif [[ $num =~ ^[[:digit:]]{2}$ ]]; then
printf '\nDOUBLE DIGIT NUMBER!'
elif [[ $num =~ ^[[:digit:]]{3}$ ]]; then
printf '\nTRIPLE DIGIT NUMBER!'
else
printf >&2 '\nINVALID INPUT!'
fi
Upvotes: 1
Reputation: 50775
I'd validate the input first.
case $num in
*[!0-9]*|????*) ;; # invalid input
?) ;; # single digit
??) ;; # double digit
???) ;; # triple digit
esac
Upvotes: 4
Reputation: 27225
[]
is a character class. The -
for specifying ranges only handles characters, not integers. [100-999]
is a character class with …
1
, 0
0-9
9
and 9
… so basically [0-9]
.
As pointed out by Jetchisel, use [0-9][0-9]
and [0-9][0-9][0-9]
.
Upvotes: 2