Using getopts to pass parameters in bash scripts

Twitter

    Current Desktop

    Where to find me

    diveli is Mig, a French-Australian sysadmin & Drupal developer living in Melbourne, Australia.




    On Twitter
    On Last.fm
    On StumbleUpon
    On Debian Administration
    On Drupal.org
    On Flickr

    Recent comments

    I always wondered how scripts passed variables beginning with a '-', i.e 'foo.sh -q', or 'tar -zxfv' and so on.

    I knew that '$1' in bash takes the first extra variable sent at the shell, but that can be any sort of word, not specifically a '-' parameter. Does that make sense?

    Anyway, it turns out you can use this neat getopts function like so, with a case statement. This way you can also output a 'usage' mini-manual when a variable that is unrecognised, is passed:

    usage()
    {
    cat << EOF
    usage: $0 -option
     
    Use this script to rsync this to that :)
     
    OPTIONS:
       -v      Be verbose, see what is transferring
       -q      Be quiet, hide transfer info except errors
    EOF
    }
     
    while getopts ":vq" optname
      do
        case $optname in
          v)
            rsync -aHPv /path/to/dir remote:/path/to/
            ;;
          q)
            rsync -aHPq /path/to/dir remote:/path/to/
            ;;
          ?)
            usage
            exit
            ;;
        esac
      done

    The ':' at the start of the getopts string sets '?' as parameter if it is unrecognised. You then use '?)' in the case statement to catch these erroneous paramaters (if I've understood all this correctly)

    A much more concise explanation is offered here.

    Comments

    Post new comment

    The content of this field is kept private and will not be shown publicly.
    • Web page addresses and e-mail addresses turn into links automatically.
    • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
    • Lines and paragraphs break automatically.

    More information about formatting options

    CAPTCHA
    This question is for testing whether you are a human visitor and to prevent automated spam submissions.