Parsing shell script arguments

后端 未结 4 1786
渐次进展
渐次进展 2020-12-14 11:35
$myscript.sh -host blah -user blah -pass blah

I want to pass arguments into it.

I\'m used to doing $1, $2,

相关标签:
4条回答
  • 2020-12-14 12:30

    man getopt

    0 讨论(0)
  • 2020-12-14 12:30

    Here is a simple way to handle both long and short options:

    while [[ $1 == -* ]]; do
        case "$1" in
          -h|--help|-\?) show_help; exit 0;;
          -v|--verbose) verbose=1; shift;;
          -f) if (($# > 1)); then
                output_file=$2; shift 2
              else 
                echo "-f requires an argument" 1>&2
                exit 1
              fi ;;
          --) shift; break;;
          -*) echo "invalid option: $1" 1>&2; show_help; exit 1;;
        esac
    done
    

    From How can I handle command-line arguments (options) to my script easily?

    0 讨论(0)
  • 2020-12-14 12:33

    There are lots of ways to parse arguments in sh. Getopt is good. Here's a simple script that parses things by hand:

    #!/bin/sh
    # WARNING: see discussion and caveats below
    # this is extremely fragile and insecure
    
    while echo $1 | grep -q ^-; do
        # Evaluating a user entered string!
        # Red flags!!!  Don't do this
        eval $( echo $1 | sed 's/^-//' )=$2
        shift
        shift
    done
    
    echo host = $host
    echo user = $user
    echo pass = $pass
    echo args = $@
    

    A sample run looks like:

    $ ./a.sh -host foo -user me -pass secret some args
    host = foo
    user = me
    pass = secret
    args = some args
    

    Note that this is not even remotely robust and massively open to security holes since the script eval's a string constructed by the user. It is merely meant to serve as an example for one possible way to do things. A simpler method is to require the user to pass the data in the environment. In a bourne shell (ie, anything that is not in the csh family):

    $ host=blah user=blah pass=blah myscript.sh
    

    works nicely, and the variables $host, $user, $pass will be available in the script.

    #!/bin/sh
    echo host = ${host:?host empty or unset}
    echo user = ${user?user not set}
    ...
    
    0 讨论(0)
  • 2020-12-14 12:34

    I adopt above William Pursell example (with Dennis Williamson advice) for parameters in this format: script -param1=value1 -param2=value2 ...

    Here is code with one-line arguments parser (save it in file 'script'):

    #!/bin/bash
    
    while echo $1 | grep ^- > /dev/null; do declare $( echo $1 | sed 's/-//g' | sed 's/=.*//g' | tr -d '\012')=$( echo $1 | sed 's/.*=//g' | tr -d '\012'); shift; done
    
    echo host = $host
    echo user = $user
    echo pass = $pass
    

    You call it like that:

    script -host=aaa -user=bbb -pass=ccc

    and result is

    host = aaa
    user = bbb
    pass = ccc
    

    Do someone know shorter code to parse arguments than this above?

    0 讨论(0)
提交回复
热议问题