Best way to parse command line args in Bash?

前端 未结 2 1298
半阙折子戏
半阙折子戏 2020-11-30 07:11

After several days of research, I still can\'t figure out the best method for parsing cmdline args in a .sh script. According to my references the getopts cmd is the way to

2条回答
  •  感情败类
    2020-11-30 07:39

    I find the use of getopt to be the easiest. It provides correct handling of arguments which is tricky otherwise. For example, getopt will know how to handle arguments to a long option specified on the command line as --arg=option or --arg option.

    What is useful in parsing any input passed to a shell script is the use of the "$@" variables. See the bash man page for how this differs from $@. It ensures that you can process arguments that include spaces.

    Here's an example of how I might write s script to parse some simple command line arguments:

    #!/bin/bash
    
    args=$(getopt -l "searchpath:" -o "s:h" -- "$@")
    
    eval set -- "$args"
    
    while [ $# -ge 1 ]; do
            case "$1" in
                    --)
                        # No more options left.
                        shift
                        break
                       ;;
                    -s|--searchpath)
                            searchpath="$2"
                            shift
                            ;;
                    -h)
                            echo "Display some help"
                            exit 0
                            ;;
            esac
    
            shift
    done
    
    echo "searchpath: $searchpath"
    echo "remaining args: $*"
    

    And used like this to show that spaces and quotes are preserved:

    user@machine:~/bin$ ./getopt_test --searchpath "File with spaces and \"quotes\"."
    searchpath: File with spaces and "quotes".
    remaining args: other args
    

    Some basic information about the use of getopt can be found here

提交回复
热议问题