Linux脚本:命令行参数

时间:2017-06-21 20:35:08

标签: shell command arguments line

尝试编写一个只接受一个命令行参数的脚本,并且必须是一个正数。我有一个参数,但无法找出正数。 我有以下内容:

  #!/bin/ksh

  NUMBER=$1
  # Accepts only one argument or does not execute.
  if [ "$#" != 1 ]
  then
     echo "error: program must be executed with 1 argument."
     exit
  else
      if [ "$#" < 1 ] # **NEED HELP HERE**. Check for negative number.
  then
      echo "error: argument must be a positive number."
  fi
  fi
  do
         echo -n $NUMBER
         if [ $NUMBER -gt 1 ]
         then
            echo -n ", "
         fi
         NUMBER=$(($NUMBER - 1))
   done
   echo

...需要帮助识别命令行参数是否为负数。

由于

3 个答案:

答案 0 :(得分:0)

以下工作:

test "$NUMBER" -ge 0 && printf "NOT NEGATIVE" || printf "NEGATIVE"

答案 1 :(得分:0)

通过检查是否仅为数字来验证它是否为数字:

#!/bin/ksh

NUMBER=$1
# Accepts only one argument or does not execute.
if [ "$#" != 1 ]
then
  echo "error: program must be executed with 1 argument."
  exit
else
  case $NUMBER in
    ''|*[!0-9]*)
      echo "error: argument must be a positive number."
      exit
      ;;
  esac
fi

while ! [ $NUMBER -lt 1 ]
do
     echo -n $NUMBER
     if [ $NUMBER -gt 1 ]
     then
        echo -n ", "
     fi
     NUMBER=$(($NUMBER - 1))
done
echo

答案 2 :(得分:0)

假设我们只讨论正(基数10)整数......并且不包括逗号,指数表示法和前导加号(+)......

# test for ${NUMBER} containing anything other than digits 0-9
if [[ "${NUMBER}" = @(*[!0-9]*) ]]
then
    echo "error: argument is not a positive number."
else
    echo "success: argument is a positive number"
fi

显然,当您删除对定义为*有效* positive number的假设时,它会变得更有趣。

扩展sqrt163提出的解决方案...一个简单的函数应该允许我们处理指数表示法,float / real和带有前导加号(+)的数字,同时允许调用进程过滤掉有关语法错误的消息......

$cat test.sh
#!/bin/ksh
NUMBER=$1
isnumber()
{
    # following should generate a non-zero for negative and non-numerics,
    # while allowing the parent process to filter out syntax errors

    [[ "${1}" -gt 0 ]]
}

# direct isnumber() output to /dev/null since we're only interested
# in the return code, and we want to mask any syntax issues if
# isnumber() is called with a non-numeric argument; unfortunately,
# for a valid numeric that contains a comma (eg, NUMBER = 1,000)
# our isnumber() call will fail

if isnumber ${NUMBER} >/dev/null 2>&1
then
    echo "${NUMBER} is a positive number"
else
    echo "${NUMBER} is not a positive number"
fi

还有一些测试...

$ for s in 1 1.33 1e5 1e-4 +1 +1.65 +1e4 1,000 -1 -1.234 -1e5 -1,000 a b a1b ab1 1ab "a b c"
do
test.sh "$s"
done
1 is a positive number
1.33 is a positive number
1e5 is a positive number
1e-4 is a positive number
+1 is a positive number
+1.65 is a positive number
+1e4 is a positive number
1,000 is not a positive number
-1 is not a positive number
-1.234 is not a positive number
-1e5 is not a positive number
-1,000 is not a positive number
a is not a positive number
b is not a positive number
a1b is not a positive number
ab1 is not a positive number
1ab is not a positive number
a b c is not a positive number

这让我们(我相信)只包含一个包含一个或多个逗号的输入问题,这可以通过使用适合您喜欢的任何方法删除逗号来处理。