LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash: using tests in a case structure (https://www.linuxquestions.org/questions/programming-9/bash-using-tests-in-a-case-structure-4175436558/)

towardstheedge 11-10-2012 09:36 AM

Bash: using tests in a case structure
 
I am trying to simplify a series of loops by using a case structure.

This is for an optional exercise in my Linux class. I am new to Linux, bash, and programming in general. The case structure is not a requirement for the project, just something I wanted to try.

Code:

var1=0

while [ -f .tlight.run ]
do

case "$var1" in

[ "$var1" -lt 4 ] )

echo "Green"
;;

[ "$var1" -lt 6 ] )

echo "Yellow"
;;

[ "$var1" -lt 10 ] )

echo "Red"
;;

[ "$var1" -gt 9 ] )

var1=0
esac

((var1++))

sleep 1

done


Is something like this possible in case structure? I have tried several variations and keep getting errors.

catkin 11-10-2012 09:59 AM

It can be done, using the fact that bash does arithmetic evaluation of the pattern expressions and taking care to order the cases:
Code:

#!/bin/bash

var=$1
case 1 in
    $(( var < 4 )) )
      echo less than 4
      ;; 
    $(( var < 6 )) )
      echo less than 6
      ;; 
    $(( var < 10 )) )
      echo less than 10
      ;; 
    $(( var > 10 )) )
      echo greater than 10
      ;; 
    * )
      echo does not match specific cases
esac


towardstheedge 11-10-2012 02:59 PM

Thanks for the help. I got my script to work. I think it looks a lot cleaner then the bunch of nested ifs and loops.

This is the full script that works.

Code:

#!/bin/bash

#tlight
#towardstheedge
#nov 2012

clear

var1=0

while [ -f .tlight.run ]
do

case 1 in

$(( var1 < 4 )) )

echo "Green"
;;

$(( var1 < 6 )) )

echo "Yellow"
;;

$(( var1 < 10 )) )

echo "Red"
;;

$(( var1 > 9 )) )

echo "Green"
var1=0
;;
*) echo I got here somehow
#used for debugging
esac

((var1++))

sleep 1

done

There is one piece that still puzzles me:
Code:

case 1 in
I don't understand how bash is reading that line. I tried substituting different things for the '1' to see what it would do. I don't get how the 1 relates to any of the rest of the script.

Thanks again for the help.

catkin 11-10-2012 07:08 PM

1 is arithmetic true.

To see how it relates to the $(( ... )) case "patterns", run this command at the command prompt: var=3; echo $(( var1 < 4 ))


All times are GMT -5. The time now is 07:41 PM.