shell - How can I share options parsing code within bash functions when using getopts? -


how can clean options parsing code in bash function? copy-pasted number of functions need have simple "-h" flag printing usage. rather have generic routine logical equivalent of

local prefix_opt1 local prefix_opt2 .... __handle_opts "usage message" "additional getopts flags" "prefix" 

for example:

local foo_k local foo_v __handle_opts "usage: ${funcname[0]}" [-k key -v version] widget\nbuild widget using key , version." "k:v:" "foo_"  if [[ -z $foo_k ]] ;     foo_k="default value" fi ..... 

the functions "sourced" in one's dot-bashrc file.

here code looks (note: of functions take options via flags):

function kitten_pet {    local usage="usage: ${funcname[0]} [-h] <kitten>\npet kitten."    ################################################   local help=0   local error=0   local optind   local opt   while getopts ":h" opt "$@"       case $opt in        h)         echo -e "$usage"         help=1         break         ;;        \?)         echo "invalid option: -$optarg"         error=1         break         ;;     esac   done   if [ $error -gt 0 ] || [ $help -gt 0 ] ;     return 1   fi   shift $((optind-1))   ################################################    if [ $# -lt 1 ]       echo -e "$usage"     return 1   fi    __kitten_pet "$1" } 

ordinarily use node-commander or node-optimist , write script in javascript (or perhaps python) scripting needs i'm trying make bash work time. bash bashing me.

pass generic option parser list of options calling script managing.

for each option managed in calling script, create function called option_x_parser. these option parser functions should accept optional argument ($optarg), , should return 0 (success) or 1 (error).

the generic option parser should build shell case statement using generic options (e.g., "h", "n", , "v") supplied options calling program. options have associate option parser function, case statement should include invocations of option parsers.

there should case statement each configured option, should invoke user supplied functions, if defined, or managed generically setting global variables (.e.g., opt_x, x specific option).

for example:

 __handle_options "$usage", 'hni:v'

option_h_parser() { echo "$usage"; exit 1 ; } option_n_parser() { norun=1 ; return 0 ; } option_v_parser() { verbose=1 ; return 0 ; } option_i_parser() { insert_at="$1" ; return 0 ; } # invoke argument

basically, use implied function names, based on option letter.

the return value of each option parser examined generic option handler function. this:

 function_name="option_${opt}_parser" if eval "$function_name $optarg" ;   # option else   error "'$opt' parser failed."   exit 2 fi 


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -