bash

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

    Using getopts to pass parameters in bash scripts

    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 :)

    no users on the server, says a 'user' :)

    It's sad when this sort of thing makes me laugh:

    11:09 < diveli> uptime
    11:09 < poilu> 11:09:20 up 3 days, 16:18, 0 users, load average: 0.05, 0.08, 0.03

    Magic invisible poilu! Hooray for my trusty irc bot :)

    Statistics Report

    This is my Client web/database usage/bandwidth statistics script as mentioned in the Think Tank.

    Download