views:

113

answers:

5

Hi,

I'm completely new to shell and I'm trying to include a case where the function's arg #1 is greater or equal 12 then it should return 1. But the below doesn't work.

case $1 in
     -ge 12)     NUM=1 ;;
     *)   NUM=0 ;;
esac
echo $NUM
+3  A: 

Do you have to use case for some reason? If not, if seems more natural:

if [[ $1 -ge 12 ]]; then
  NUM=1
else
  NUM=0
fi

echo $NUM

With case, bash performs arithmetic expansion on both word and pattern, so you could write

case 1 in
  $(( $1 >= 12 )) )  NUM=1 ;;
  $(( $1 >=  7 )) )  NUM=2 ;;
  *)                 NUM=0 ;;
esac

Beauty is in the eye of the beholder.

Greg Bacon
Yeah, because I'll be adding a lot more conditions and case makes it look cleaner. So you're saying it's not possible with CASE?
goe
Updated. I'm not sure if the extra syntactic noise produces a cleaner result, but I hope it helps!
Greg Bacon
A: 

Case needs to take a pattern expression, e.g. a string.

I either recommend using a simple if statement:

if [[ $1 -ge 12 ]]; then
  NUM=1
else
  NUM=0
fi

Or express the branches in pattern expressions:

case "$1" in
     [0-9])             NUM=1   ;;
     1[0-2])            NUM=1   ;;
     *)                 NUM=0   ;;
echo $NUM
notnoop
That's equivalent to `-le`
Dennis Williamson
+3  A: 

The case statement does not interpret operators like -ge. From the bash man page:

   case word in [ [(] pattern [ | pattern ] ... ) list ;; ] ... esac
          A case command first expands word, and tries to match it 
          against each pattern in  turn,  using the same matching rules as 
          for pathname expansion (see Pathname Expansion below).

You should use a conditional expression in an if statement.

Jim Garrison
Keep reading: "Each *pattern* examined is expanded using tilde expansion, parameter and variable expansion, arithmetic substitution, command substitution, and process substitution."
Greg Bacon
arithmetic substitution is not the same as evaluation of conditional expressions. There's nothing implying that -ge is supported here.
Jim Garrison
A: 
case "$1" in
     [0-9]|1[01])NUM=0   ;;
     *) NUM=1   ;;
echo $NUM
That's equivalent to `-le`
Dennis Williamson
thks. changed for -ge
What about >99? What about 30, 31, 40, 41...?
Dennis Williamson
There, that's got it.
Dennis Williamson
A: 

You want to use the program /usr/bin/test:

if test "$1" -ge 12; then NUM=1; else NUM=2; fi
Amadeus
No, you don't .
Dennis Williamson
there's no need to use external test..!!
Care to explain why not? Using `test` is portable and it is more Unixy, i.e. to have tools that do one thing well and not have the shell be able do everything, unless you are talking about Perl :p
Amadeus