views:

84

answers:

4

When I pass in 2009 as a arg to this shell function it returns 0, why?

isyear()
{
 case $arg in
  [0-9][0-9][0-9][0-9]) NUM=1 ;;
  *)   NUM=0 ;;
 esac
 echo $arg
}
A: 

Nevermind, it should be $1 and not $arg and echo $NUM.

goe
you know, you can edit your question.
glenn jackman
+2  A: 

You likely mean $1 instead of $arg. $arg isn't defined anywhere and $1 is the first argument to the function.

jamessan
A: 

Do you mean to use return instead of echo?

  return [n]
         Causes  a function to exit with the return value specified by n.
         If n is omitted, the return status is that of the  last  command
         executed  in the function body.
Greg Hewgill
The only problem with using `return` is that it will only return values in the range 0-255. That's why `echo` is often used. In the case of this question, however, it's sufficient.
Dennis Williamson
and he probably wants `return $NUM` anyway
glenn jackman
+1  A: 

Two typos: First of all you need to use $1 not $arg to get the first parameter of the function. Secondly I think you meant to echo $NUM rather than the passed-in argument!

isyear() {
      case $1 in
              [0-9][0-9][0-9][0-9])   NUM=1   ;;
              *)                      NUM=0   ;;
      esac
      echo $NUM 
}

You might also consider reworking it like this:

#!/bin/bash

isyear() {
    case $1 in
          [0-9][0-9][0-9][0-9])   return 1 ;;
          *)                      return 0 ;;
    esac
}

isyear cheese
if [ "$?" -eq "1" ]; then
  echo "Yes, it is a year!"
else
  echo "Darn!"
fi

isyear 2009
if [ "$?" -eq "1" ]; then
  echo "Yes, it is a year!"
else
  echo "Darn!"
fi
Christopher Gutteridge