Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using case for a range of numbers in Bash

I am trying to do the following using case in Bash (in Linux).

If X is between 460 and 660, output X information.

If X is between 661 and 800, do something else.

Etc.

Right now this is what I have:

case $MovieRes in
    [461-660]*) echo "$MovieName,480p" >> moviefinal ;;
    [661-890]*) echo "$MovieName,720p" >> moviefinal ;;
    [891-1200]*) echo "$MovieName,1080p" >> moviefinal ;;
    *) echo "$MovieName,DVD" >> moviefinal ;;
esac

But somehow many of the ones that are 480p, 720p or 1080p are ending with DVD instead. The variable $MovieRes is a simple list that shows, for each line, a number between 1 and 1200. Depending on the value, case decides which "case" to apply.

I would like to know how to actually use case to accomplish this since it is a bit confusing when dealing with ranges like this.

like image 789
Luis Alvarado Avatar asked Sep 27 '12 04:09

Luis Alvarado


2 Answers

In bash, you can use the arithmetic expression: ((...))

if ((461<=X && X<=660))
then
    echo "480p"
elif ((661<=X && X<=890))
then
    echo "720p"
elif ((891<=X && X<=1200))
then
    echo "1080p"
else
    echo "DVD"
fi >> moviefinal
like image 178
kev Avatar answered Oct 06 '22 01:10

kev


The bash case statement doesn't understand number ranges. It understands shell patterns.

The following should work:

case $MovieRes in
    46[1-9]|4[7-9][0-9]|5[0-9][0-9]|6[0-5][0-9]|660) echo "$MovieName,480p" >> moviefinal ;;
    66[1-9]|6[7-9][0-9]|7[0-9][0-9]|8[0-8][0-9]|890) echo "$MovieName,720p" >> moviefinal ;;
    89[1-9]|9[0-9][0-9]|1[0-1][0-9][0-9]|1200)       echo "$MovieName,1080p" >> moviefinal ;;
    *)                                               echo "$MovieName,DVD" >> moviefinal ;;
esac

However, I'd recommend you use an if-else statement and compare number ranges as in the other answer. A case is not the right tool to solve this problem. This answer is for explanatory purposes only.

like image 35
dogbane Avatar answered Oct 05 '22 23:10

dogbane