goe
goe

Reputation: 5435

Case statement in shell - problem

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

Upvotes: 0

Views: 2736

Answers (5)

ghostdog74
ghostdog74

Reputation: 342977

case "$1" in
     [0-9]|1[01])NUM=0   ;;
     *) NUM=1   ;;
echo $NUM

Upvotes: 0

Hai-Anh Trinh
Hai-Anh Trinh

Reputation: 1182

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

if test "$1" -ge 12; then NUM=1; else NUM=2; fi

Upvotes: 0

Greg Bacon
Greg Bacon

Reputation: 139681

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.

Upvotes: 3

Jim Garrison
Jim Garrison

Reputation: 86774

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.

Upvotes: 3

notnoop
notnoop

Reputation: 59307

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

Upvotes: 0

Related Questions