An example of how to use getopts in bash

前端 未结 7 2383
小蘑菇
小蘑菇 2020-11-22 07:35

I want to call myscript file in this way:

$ ./myscript -s 45 -p any_string

or

$ ./myscript -h  #should display         


        
7条回答
  •  执笔经年
    2020-11-22 07:53

    POSIX 7 example

    It is also worth checking the example from the standard: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html

    aflag=
    bflag=
    while getopts ab: name
    do
        case $name in
        a)    aflag=1;;
        b)    bflag=1
              bval="$OPTARG";;
        ?)   printf "Usage: %s: [-a] [-b value] args\n" $0
              exit 2;;
        esac
    done
    if [ ! -z "$aflag" ]; then
        printf "Option -a specified\n"
    fi
    if [ ! -z "$bflag" ]; then
        printf 'Option -b "%s" specified\n' "$bval"
    fi
    shift $(($OPTIND - 1))
    printf "Remaining arguments are: %s\n" "$*"
    

    And then we can try it out:

    $ sh a.sh
    Remaining arguments are: 
    $ sh a.sh -a
    Option -a specified
    Remaining arguments are: 
    $ sh a.sh -b
    No arg for -b option
    Usage: a.sh: [-a] [-b value] args
    $ sh a.sh -b myval
    Option -b "myval" specified
    Remaining arguments are: 
    $ sh a.sh -a -b myval
    Option -a specified
    Option -b "myval" specified
    Remaining arguments are: 
    $ sh a.sh remain
    Remaining arguments are: remain
    $ sh a.sh -- -a remain
    Remaining arguments are: -a remain
    

    Tested in Ubuntu 17.10, sh is dash 0.5.8.

提交回复
热议问题