如何在bash脚本中编写getopt

时间:2015-08-07 12:34:07

标签: bash shell getopt getopts getopt-long

我有一个带有一些参数的函数。例如:

{
  "query": {
    "filtered": {
      "query": {
        "bool": {
          "must_not": [
            { wildcard: {url: "*.biz"} }
          ]
        }
      },
      "filter": {
        "bool": {
          "must_not": [
            {ids: {values: ["one", "two"]}
          ]
        }
      }
    }
  }
}

我想制作makeUser{ login email password} -l|--login-e|--email等标记,但我不知道如何。

它的示例应如下所示:

-p|--password

如何实现这一结果?我只知道如何使用getopts(短旗)。

它应该看起来像下面的代码吗?

./script.sh --mode makeUser --login test --email test@test.com -p testxx

1 个答案:

答案 0 :(得分:1)

使用whileshift为bash中的getopt-like行为提供了一个干净的解决方案:

while [ $# -gt 0 ]; do
    case "$1" in
        -h|"-?"|--help)
            shift
            echo "usage: $0 [-v] [--mode MODE] [-l login] [-e email] [...]"
            exit 0
            ;;
        --mode)
            MODE=$2
            shift; shift;
            ;;
        -l|--login)
            LOGIN=$2
            shift; shift;
            ;;
        -e|--email)
            EMAIL=$2
            shift; shift;
            ;;
        -v|--verbose)
            VERBOSE=1
            shift;
            ;;
         *)
            echo "Error: unknown option '$1'"
            exit 1
        esac
done

# example function makeUser
makeUser()
{
    login=$1
    email=$2

    echo "function makeUser with login=${login} and email=${email}"
}


if [ "$MODE" == "makeUser" ]; then
    makeUser $LOGIN $EMAIL # ... and so on
fi