Sunday, July 16, 2017

Bash Options Handler

#!/usr/bin/env bash

#############################################################################
###########################################################################
### Created by A.M.Danischewski (c) 2017+ v1.00
### Issues: If you find any issues emai1 me at my <first name> dot 
###         <my last name> at gmail dot com.  
###
### This is a simple effective options handler, that easily and 
### automatically handles long and short options. Hack away at it! =) 
### 
### E.g. options_handler.bsh -e e_value -l --super s_value of default 
###      options_handler.bsh --extended e_value dispersed -l -s s_value default value 
### This program is free software: you can redistribute it and/or modify. 
###########################################################################
#############################################################################

declare -a OPTIONS
declare -A OPTIONVALUES
declare -i DEFAULT_OPTION_SET=0 
declare -r DEFAULT_INDEX="default"

 ### This is a commandline options handler, it loads two arrays the first 
 ### array OPTIONS holds the OPTION FLAGS that were passed. The second 
 ### array is an associative array that holds option arguments if any 
 ### that were passed in. 
 ### Note: This handler does not accept spaces in long option names. 
function process_options() { 
while (($#>0)); do
case "$1" in
    -e|--extended)
    OPTIONS+=("-e")
     ## No argument option. 
    #[[ ! "$2" =~ ^- ]] && OPTIONVALUES["-e"]="$2" && shift 
    ;;
    -s|--super)
    OPTIONS+=("-s")
    [[ ! "$2" =~ ^- ]] && OPTIONVALUES["-s"]="$2" && shift 
    ;;
    -l|--longoption)
    OPTIONS+=("-l")
    [[ ! "$2" =~ ^- ]] && OPTIONVALUES["-l"]="$2" && shift 
    ;;
    --default)
    ;&
    *)
    if [[ "$1" =~ ^- ]]; then ## Handle unexpected options. 
       echo "*** Error option $1 not found" >&2 
       ## Add your logic. 
       shift 
    fi 
    ## Handle the default argument. 
    ((! ${DEFAULT_OPTION_SET})) && OPTIONS+=("${DEFAULT_INDEX}") && DEFAULT_OPTION_SET=1
    while [[ ! "$1" =~ ^- ]] && [[ $# -gt 0 ]]; do ## Look ma, no quotes. o_0
     OPTIONVALUES["${DEFAULT_INDEX}"]+=" ${1}" && shift
    done 
    [[ "$1" =~ ^- ]] && continue ## We have a flag again, skip shifting. 
    ;;
esac
shift ## Shift to next option. 
done
} 

function print_options() { 
for a in ${OPTIONS[@]}; do 
 echo "Got: $a with arg: ${OPTIONVALUES[${a}]}"
done   
}

process_options "$@" 
print_options
exit 0 

No comments:

Post a Comment