Using case for a range of numbers in Bash
I was looking for the simplest solution and found it difficult to use a case statement with a number range .
Finally i found a really simple solution for zsh :
#!/usr/bin/zsh
case "${var}" in
<0-5461>)
printf "${var} is between 0 and 5461"
;;
<5462-10922>)
printf "${var} is between 5462-10922"
;;
esac
and for Bash :
#!/bin/bash
case $((
(var >= 0 && var <= 5461) * 1 +
(var > 5462 && var <= 10922) * 2)) in
(1) printf "${var} is between 0 and 5461";;
(2) printf "${var} is between 5461 and 10922";;
esac
Hope it helps someone .
Just for the pleasure of subverting case to do as you want,
you can use $((...))
case 1 in
$(($MovieRes<= 460)))echo "$MovieName,???";;
$(($MovieRes<= 660)))echo "$MovieName,480p";;
$(($MovieRes<= 890)))echo "$MovieName,720p";;
$(($MovieRes<=1200)))echo "$MovieName,1080p";;
*)echo "$MovieName,DVD";;
esac >> moviefinal
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.
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