Using getopts to process long and short command line options

后端 未结 30 1570
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 22:52

I wish to have long and short forms of command line options invoked using my shell script.

I know that getopts can be used, but like in Perl, I have not

30条回答
  •  旧巷少年郎
    2020-11-21 23:25

    Take a look at shFlags which is a portable shell library (meaning: sh, bash, dash, ksh, zsh on Linux, Solaris, etc.).

    It makes adding new flags as simple as adding one line to your script, and it provides an auto generated usage function.

    Here is a simple Hello, world! using shFlag:

    #!/bin/sh
    
    # source shflags from current directory
    . ./shflags
    
    # define a 'name' command-line string flag
    DEFINE_string 'name' 'world' 'name to say hello to' 'n'
    
    # parse the command-line
    FLAGS "$@" || exit 1
    eval set -- "${FLAGS_ARGV}"
    
    # say hello
    echo "Hello, ${FLAGS_name}!"
    

    For OSes that have the enhanced getopt that supports long options (e.g. Linux), you can do:

    $ ./hello_world.sh --name Kate
    Hello, Kate!
    

    For the rest, you must use the short option:

    $ ./hello_world.sh -n Kate
    Hello, Kate!
    

    Adding a new flag is as simple as adding a new DEFINE_ call.

提交回复
热议问题