Bash long options/flags - how to do it?
Asked Answered
N

1

3

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!

Nicolasanicolau answered 7/8, 2015 at 5:30 Comment(0)
R
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.

Russia answered 12/10, 2015 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.