Bash 具有 getopts/flags 和多项功能

Bash with getopts/flags and multiple functions

我对 getopts 有疑问。当我写 ./nameofscript.sh -n name - 它应该创建一个新的存储库但它对我说:-- n is unknown option and in new line: Adding user with name: blank.

为什么会这样?

    #!/bin/bash


    #what2do=${0##*/}
    #what2do=${what2do%.sh}


    what2do="addProject"
    what2do="addRepository"
    what2do="addUser"


    doAddRepository ()  {
     local repoName=""
    echo "Adding repo with name: $repoName"
     # Adding new repository with the name $repoName...
    }
    doAddProject ()  {
     local projName=""
    echo "Adding project with name: $projName"
     # Adding new project with the name $projName...
    }
    doAddUser ()  {
     local userName=""
    echo "Adding user with name: $userName"
     # Some code to add user "$userName"...
    }

case $what2do in
addRepository)
      while getopts 'n:' key; do
        case $key in
          n) REPO_NAME=$OPTARG ;;
        esac
      done
      doAddRepository "$REPO_NAME"
      exit $?
    ;;
addProject)
      while getopts 'm:' key; do
        case $key in
          m) PROJ_NAME=$OPTARG ;;
        esac
      done
      doAddProject "$PROJ_NAME"
      exit $?
    ;;
addUser)
      while getopts 'u:' key; do
        case $key in
          u) USER_NAME=$OPTARG ;;
        esac
      done
      doAddUser "$USER_NAME"
      exit $?
    ;;
    *)
      echo "I don't know how to $what2do. Maybe, it is NIY" >&2
    #  doShowUsage
      exit 1
    ;;
esac

问题是您在代码开头定义了 what2do 变量 3 次:

what2do="addProject"
what2do="addRepository"
what2do="addUser

what2do 变量的最终值为 addUser。以下代码在 case 块中执行。需要 -u 选项。

enteraddUser)
  while getopts 'u:' key; do
    case $key in
      u) USER_NAME=$OPTARG ;;
    esac
  done
  doAddUser "$USER_NAME"
  exit $?

以下是代码示例:

    #!/bin/bash

    what2do="addProject"
    what2do="addRepository"
    what2do="addUser"


    doAddRepository ()  {
     local repoName=""
    echo "Adding repo with name: $repoName"
     # Adding new repository with the name $repoName...
    }
    doAddProject ()  {
     local projName=""
    echo "Adding project with name: $projName"
     # Adding new project with the name $projName...
    }
    doAddUser ()  {
     local userName=""
    echo "Adding user with name: $userName"
     # Some code to add user "$userName"...
    }

getopts 'm:' mode
modeValue=$OPTARG

getopts 'p:' paremter
parameterValue=$OPTARG

case $modeValue in
addRepository)
      doAddRepository "$parameterValue"
      exit $?
    ;;
addProject)
      doAddProject "$parameterValue"
      exit $?
    ;;
addUser)
      doAddUser "$parameterValue"
      exit $?
    ;;
    *)
      echo "I don't know how to $modeValue. Maybe, it is NIY" >&2
    #  doShowUsage
      exit 1
    ;;
esac

用法如下:

./script.sh -m addProject -p ProjectName
./script.sh -m addUser -p UserName
./script.sh -m addRepository -p RepositoryName