Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

My target is to verify a range of number with (only with case + esac), and print the range. So for example:

  • If the number is between 0 and 80, print >=0<=80
  • If the number is between 81 and 100 then print >=81<=100
  • etc.

The problem with my script below print only >=0<=90 only if the number between 0 and 9. How to fix my script, so that it will print correct output according to the number range?

#!/bin/ksh
read number 
case $number in 
 [0-80])  echo ">=0<=80";; 
 [81-100]) echo ">=81<=100";; 
 [101-120]) echo ">=101<=120";;
 [121-300]) echo ">=121<=300";;
esac
share|improve this question

2 Answers 2

up vote 2 down vote accepted

case is only for pattern matching, it won't do arithmetic evaluation (except maybe if you consider zsh's <x-y> extended pattern matching operator).

You could match numbers with patterns like:

case $(($number)) in
  ([0-9]|[1-7][0-9]|80) echo ">=0<=80";;
  (8[1-9]|9[0-9]|100) echo ">=81<=100";;
  ... and so on
esac

But you can easily see that it's not the right tool.

The [...] matches one character against the list of specified characters, so [121-300] matches for any character that is either 1, 2, 1 to 3, 0 or 0, so it's the same as [0-3] or [0123].

Use:

if [ "$number" -ge 0 ] && [ "$number" -le 80 ]; then
  echo ">=0<=80"
elif [ "$number" -ge 81 ] &&  [ "$number" -le 100 ]; then
  echo ">=81<=100"
elif ... and so on
  ...
fi
share|improve this answer
    
+1, consider if [ n < 0 ] - elif [ n <= 80 ] - elif [ n <= 100 ] ... - else. Less typing, less error-prone. –  peterph Feb 19 '13 at 12:29

This is not very nice but you can use this :

 #!/bin/ksh

read number  

case $number in
[0-9]|[1-7][0-9]|80) echo  echo ">=0<=80";;
8[1-9]|9[0-9]|100) echo ">=81<=100";;
10[1-9]|11[0-9]|120) echo ">=101<=120";;
12[1-9]|130) echo ">=121<=300";;
esac
share|improve this answer
    
You may want to "canonify" the number with $(($number)) to cover for numbers like "001" or "0x99"... That would also cover for " 12" and "12+12" which may or may not be desirable. –  Stéphane Chazelas Feb 19 '13 at 12:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.