is_number函数对我不起作用 - unix shell

时间:2009-11-28 20:39:30

标签: shell numbers unix

当我在2009年作为arg传递给这个shell函数时,它返回0,为什么?

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

4 个答案:

答案 0 :(得分:2)

您可能意味着$1而不是$arg$arg未在任何地方定义,$1是函数的第一个参数。

答案 1 :(得分:1)

您的意思是使用return代替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.

答案 2 :(得分:0)

没关系,它应该是$ 1而不是$ arg和echo $ NUM。

答案 3 :(得分:0)

两个拼写错误: 首先,你需要使用$ 1而不是$ arg来获取函数的第一个参数。 其次,我认为你的意思是回应$ NUM而不是传入的参数!

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

你也可以考虑像这样重做:

#!/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