简单的bash shell脚本确保提供两个参数

时间:2016-06-20 04:54:08

标签: bash shell scripting

我试图在bash中编写简单的问候语脚本,以确保用户提供至少两个参数。 1)第一个参数提供了在打印问候语之前我们想要延迟多长时间。 2)第二个参数提供了我们想要显示的消息。对不起,我是shell脚本的新手。

#!/bin/sh
if[$# -ge 2]
then
   sleep $1
   shift
   banner $*
else
   echo "Usage: Greeing seconds word(s)"
fi

2 个答案:

答案 0 :(得分:5)

您应该使用:

#!/bin/sh
if [ $# -ge 2 ]
then
    sleep $1
    shift
    banner $*
else
    echo "Usage: Greeing seconds word(s)"
fi

你错过了:

  • if
  • 之后的空格
  • []
  • 周围的空格

答案 1 :(得分:3)

如果要确保给出2个参数,请使用${2?}。例如:

echo First arg is ${1?Missing first argument}.  2nd arg is ${2?Missing 2nd argument}