Bash long options/flags - how to do it?

こ雲淡風輕ζ 提交于 2019-12-10 19:29:36

问题


I am trying to change my working script with getopts to getopt ( long flags ). Below i present my code which is working.

getopts 'm:' mode
modeValue=$OPTARG

getopts 'p:' parameter
parameterValue=$OPTARG

getopts 'u:' parameter
parameterValue2=$OPTARG

getopts 'l:' parameter 
parameterValue3=$OPTARG

getopts 'n:' parameter 
parameterValue4=$OPTARG

getopts 'e:' parameter 
parameterValue5=$OPTARG

getopts 'w:' parameter 
parameterValue6=$OPTARG

getopts 'r:' parameter 
parameterValue7=$OPTARG

case $modeValue in
    addRepository)
          doAddRepository "$parameterValue" "$parameterValue7"
          exit $?
        ;;
    addProject)
          doAddProject "$parameterValue"
          exit $?
        ;;
    addUser)
          doAddUser "$parameterValue2" "$parameterValue4" "$parameterValue5" "$parameterValue6"
          exit $?
        ;;
    assignProject)
          doAssignProject "$parameterValue" "$parameterValue2" "$parameterValue3"
          exit $?
        ;;
    *)
          #echo "$doShowUsage"    
          exit 1
        ;;
esac

Now my script is working like example below:

For add repository: ./script.sh -m addRepository -p NameOfTheProject -r NameOfTheRepository

I want to edit this for something like this:

./script.sh --mode addRepository --project NameOfTheProject --repo NameOfTheRepository

I started to modify code and added something what i present below:

 TEMP=`getopt -o m:p:u:l:n:e:c:r: --long mode:,project:,username:,level:,name:,email:,pass:,repo: -n 'test.sh'
    -- "$@"` eval set -- "$TEMP"

while true ; do
    case "$1" in
        -m|--mode)
            case "$2" in
                addRepository)
                        doAddRepository=$2 ; shift 2 ;;
                addProject)
                        doAddProject=$2 ; shift 2 ;;
                addUser)
                        doAddUser=$2 ; shift 2 ;;
                assignProject)
                        doAssignProject=$2 ; shift 2 ;;
                esac ;;
        -h|--help)
            case "$2" in
                *) echo "$doShowUsage"
                   exit 1
                esac ;;
        esac done

My question is : Am I doing it in the right way ? How can I add parameters to the functions "doAddProject/Repository/User...?" Can someone give me some advices? Above functions got different amount of parameters so take a look at it.

Thank you!


回答1:


Stephane Chazelas wrote a very fine getops-long shell script that I use in my bash debugger. You can copy that script and use it.

If you run that program setting variable test_getopts_long, e.g.

test_getopts_long=1 bash getopts_long.sh

you'll see extensive examples for how to use, and it tests itself.



来源:https://stackoverflow.com/questions/31870341/bash-long-options-flags-how-to-do-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!