Bash Command Line Arguments

I was reading a blog a while back (I follow about 30 of them) where the author made a comment about how he uses his blog as a place to take notes for himself as well as anyone else who might have the same problems that he does.  I’ve meant to do this many times before but have never actually done it….until now.

I frequently write BASH scripts for use at work.  I am a firm believer that if I am going to do something more than once or twice, script the stupid thing out.  When possible, I’m a big fan of using command line arguments when I write scripts just to make things easier and also allow even more scripting, but I always forget how the hell to handle the things…..No more.  The script below is a bit of code to take in command line arguments and parse them properly.  The code came from a script I am working on with a friend to automate the installation of Splunk (will post it when it’s done).

#Parse Command Line Options
while [ "$1" != "" ];  do
    case $1 in
        -f | --forwarder )
            INSTALL_TYPE=4
            ;;
        -h | --help )
            usage
            ;;
        -i | --indexer )
            INSTALL_TYPE=2
            ;;
        -l | --license )
            shift
            LICENSE_LOC=$1
            ;;
        -m | --master )
            INSTALL_TYPE=1
            ;;
        -s | --search )
            INSTALL_TYPE=3
            ;;
        --single )
            INSTALL_TYPE=5
            ;;
        * )
            usage
            exit 1
            ;;
    esac
    shift
done

usage () {
    echo "Splunk Automated Installer"
    echo 
    echo "Usage:  headless_install.sh [OPTIONS]"
    echo
    echo "  -f, --forwarder            Install Forwarder"
    echo "  -h, --help                 Display Help Menu"
    echo "  -i, --indexer              Install Indexer"
    echo "  -l, --license <file path>  License Location"
    echo "  -m, --master               Install Master"
    echo "  -s, --search               Install Search Head"
    echo "  --single                   Install Standalone"
}

Of note is line 13 which receives the location of a license file.  First it gets the switch (-l or –license) and the shifts to the next bit of input which is the actual location of the file.  Fingers crossed I won’t waist time Googling this again.

Computer Code

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>