Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make case statement match a number range?

I'm running a switch case with column numbers which can be in the range 0 - 50. Now each case supports discrete column number and I observe its failure.

Here is the code:

    i=10     a=1     b=0.65     if [ "$a" != "$b" ]; then         case $i in               [1]|[2]|[5]) echo "Not OK"; ;;              [9-10]|[12]) echo "may be ok"; ;;              *) echo "no clue - $i"; ;;         esac    fi 

I expect this code to output may be ok but get no clue - 10.

like image 313
shamik Avatar asked Aug 25 '14 08:08

shamik


People also ask

Can switch case have range?

Using range in switch case in C/C++ You all are familiar with switch case in C/C++, but did you know you can use range of numbers instead of a single number or character in case statement.

How do you use a range of a number switch?

Using range in switch case in C/C++ In the switch statement we pass some value, and using different cases, we can check the value. Here we will see that we can use ranges in the case statement. After writing case, we have to put lower value, then one space, then three dots, then another space, and the higher value.


1 Answers

Bash case doesn't work with numbers ranges. [] is for shell patterns.

for instance this case [1-3]5|6) will work for 15 or 25 or 35 or 6.

Your code should look like this:

i=10 a=1 b=0.65 if [ "$a" != "$b" ] ; then    case $i in         1|2|5) echo "Not OK"; ;;         9|10|12) echo "may be ok"; ;;         *) echo "no clue - $i"; ;;    esac; fi 

If i can be real between 9 and 10 then you'll need to use if (instead of case) with ranges.

like image 145
Arnon Zilca Avatar answered Sep 29 '22 08:09

Arnon Zilca