Using getopts to process long and short command line options

后端 未结 30 1618
佛祖请我去吃肉
佛祖请我去吃肉 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:22

    In case you don't want the getopt dependency, you can do this:

    while test $# -gt 0
    do
      case $1 in
    
      # Normal option processing
        -h | --help)
          # usage and help
          ;;
        -v | --version)
          # version info
          ;;
      # ...
    
      # Special cases
        --)
          break
          ;;
        --*)
          # error unknown (long) option $1
          ;;
        -?)
          # error unknown (short) option $1
          ;;
    
      # FUN STUFF HERE:
      # Split apart combined short options
        -*)
          split=$1
          shift
          set -- $(echo "$split" | cut -c 2- | sed 's/./-& /g') "$@"
          continue
          ;;
    
      # Done with options
        *)
          break
          ;;
      esac
    
      # for testing purposes:
      echo "$1"
    
      shift
    done
    

    Of course, then you can't use long style options with one dash. And if you want to add shortened versions (e.g. --verbos instead of --verbose), then you need to add those manually.

    But if you are looking to get getopts functionality along with long options, this is a simple way to do it.

    I also put this snippet in a gist.

提交回复
热议问题