Categories
Freebsd

Creating command line options in a bash script

Ok, so for a while I have done this a bunch of different ways but I think the best way I found is with a simple case statement. In here you can set variables, execute commands, functions, nest statements etc… It works out really well. here is a snippet to show you what i mean.

while [ $# -gt 0 ]
do
        case $1
        in
        -v)
                VERBOSE=YES
                shift 1
     
        ;;

        -l)
                echo "$MODULES"
                exit 0
        ;;

        -os)
                if [ -z $2 ]
                then
                        echo "You must choose a VERSION"
                        exit 1
                else
                        for MOD in $MODULES
                        do
                                if [ "$MOD" = "$2" ]
                                then
                                        LISTED=YES
                                fi
                        done
                        if [ "$LISTED" = "YES" ]
                        then
                                VERSION=$2
                                shift 2
                        else
                                echo "Module not found. Use -l for listing"
                                exit 1
                        fi
                fi
        ;;

        -h)
                HELPMENU
                exit 1
        ;;

        –help)
                HELPMENU
                exit 1
        ;;

        *)
                HELPMENU
                exit 1
        ;;
        esac
done