Search code examples
linuxbashshellunix

Parsing shell script arguments


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

I want to pass arguments into it.

I'm used to doing $1, $2, $3....but I want to start naming them


Solution

  • 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}
    ...