2014-09-13 79 views
2

我已经看到了如何使用getopts例子很多。但是我知道bash的基本知识,而且我无法在我的情况下实施它。我真的很感激,如果有人能告诉我模板。如何在bash中使用getopts来解析脚本参数?

我有一个脚本,至少有和最大输入。这里是一个简要说明:

script.sh -P passDir -S shadowDir -G groupDir -p password -s shadow 

用户必须为-P -S -G提供参数,如果不是我必须显示的使用和关闭程序。如果提供参数,我需要将它们保存到适当的变量中。

-p-s是可选的。然而,如果没有-p我应该做一些任务,如果没有-s我应该做一些其他任务,如果没有他们的存在是我应该做一些其他任务。 下面是我到目前为止写,但在for循环它的股票。

#!/bin/bash 

if [ "$(id -u)" != "0" ]; then 
    echo "Only root may add a user to system" 
    exit 2 
else 
    usage() { echo "Usage: $0 [-P <password file path>] [-S <shadow file path>] [-G <group path>]" 1>&2; exit 1; } 
    passDir="" 
    shadowDir="" 
    groupDir="" 
    while getopts ":P:S:G:" inp; do 
     case "${inp}" in 
      P) 
       $passDir = ${OPTARG};; 
      S) 
       $shadowDir = ${OPTARG};; 
      G) 
       $groupDir = ${OPTARG};; 
      *) 
       usage;; 

     esac 
    done 

    echo "${passDir}" 
    echo "${shadowDir}" 
    echo "g = ${groupDir}" 
fi 

此刻用户不输入参数什么都不会显示,如果有参数它会进入一个循环!

回答

3

据我所知,你只是缺少一些if语句来处理缺少参数。考虑:

usage() { echo "Usage: $0 [-P <password file path>] [-S <shadow file path>] [-G <group path>]" 1>&2; exit 1; } 

if [ "$(id -u)" != "0" ]; then 
    echo "Only root may add a user to system" 
    exit 2 
fi 
passDir="" 
shadowDir="" 
groupDir="" 
while getopts "P:S:G:" inp; do_ 
    case "${inp}" in 
     P) 
      passDir=${OPTARG};; 
     S) 
      shadowDir=${OPTARG};; 
     G) 
      groupDir=${OPTARG};; 
     *) 
      usage;; 
    esac 
done 

if [ -z "$passDir" ] && [ -z "$shadowDir" ] 
then 
    # if none of them is there I should do some other tasks 
    echo do some other tasks 
elif ! [ "$passDir" ] 
then 
    # if there is no -p I should do some tasks_ 
    echo do some tasks 
elif ! [ "$shadowDir" ] 
then 
    #if there is no -s I should do some other tasks 
    echo do some other tasks 
fi 
2

我固定的几件事情在你的脚本。这个工作对我来说:

#!/bin/bash 

if [ "$(id -u)" != "0" ]; then 
    echo "Only root may add a user to system" 
    exit 2 
fi 

usage() { echo "Usage: $0 [-P <password file path>] [-S <shadow file path>] [-G <group path>]" 1>&2 
    exit 1 
} 

passDir="" 
shadowDir="" 
groupDir="" 
while getopts ":P:S:G:" inp; do 
    case "${inp}" in 
     P) 
      passDir=${OPTARG};; 
     S) 
      shadowDir=${OPTARG};; 
     G) 
      groupDir=${OPTARG};; 
     *) 
      usage;; 

    esac 
done 

echo "p = $passDir" 
echo "s = $shadowDir" 
echo "g = $groupDir" 
  • 分配不能包含空格:a=1作品,a = 1
  • 变量名称不应该用$在分配前缀
  • 如果您if分支包含exit声明,则不需要将其余代码放在else分支中
+0

感谢您的回答。我很感激。我选择了其他答案作为解决方案,因为它解释了-s和-p的解决方案并未提供。再次感谢 – Bernard 2014-09-13 18:42:38

+1

@Bernard:现在你必须添加'-p密码'和'-s阴影'的例子。不要忘记写一个有用的使用信息。 – 2014-09-13 23:02:01