如何在bash中使用getopts来解析脚本参数?

时间:2014-09-13 17:31:56

标签: bash shell getopts

我见过很多关于如何使用getopts的例子。但我知道bash非常基本,我无法在我的情况下实现它。如果有专家可以向我展示模板,我真的很感激。

我有一个最小 6 和最大 10 输入的脚本。以下是简要说明:

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

目前用户没有输入参数,不会显示任何内容,如果有参数,它会进入循环!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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分支