#!/bin/bash ############################################################################### # https://github.com/adrianamaglio/driglibash-arg ############################################################################### # Usage : # # version="alpha nightly 0.0.1 pre-release unstable" # summary="$0 [options] " # # usage[t]="Start qemu after the installation" # varia[t]=tst # tst=false # # usage[i]="Install the provided package. Not implemented" # varia[i]=install # declare -a install # # usage[k]="Keep the temporar mountpoints" # varia[k]=keep # keep=false # # usage[e]="bash command file to execute in the chroot. - to read from stdin" # varia[e]=execute # declare -a execute . driglibash-base #TODO keep order usage options # Print usage and exit in error usage() { yell "Version: $version" yell "Usage: $summary" yell "Parameters:" yell " -h print this help, version and exit." for key in "${!usage[@]}" ; do if [ "$(driglibash_arg_type "$key")" == "single_value" ] ; then name="${varia[$key]}" default=" (default : ${!name})" else default= fi yell " -$key ${usage[$key]}$default" done exit 0 } # Guess the variable type # Boolean, list or string driglibash_arg_type() { if [ $# -ne 1 ] ; then die "Bad driglibash_arg_type usage"; fi name="${varia[$1]}" if [ "$name" == "" ] ; then die "Variable name is empty for key $1" ; fi if [ "${!name}" == "false" ] ; then echo "boolean" elif [ -n "$( declare -p "$name" 2>/dev/null | grep 'declare \-a')" ] ; then echo "array" else echo "single_value" fi } # Generate getopts string # getopts_string=":h" for key in ${!usage[@]} ; do needs_parameter= if [ "$(driglibash_arg_type "$key")" != "boolean" ] ; then needs_parameter=":" ; fi getopts_string="$getopts_string$key$needs_parameter" done # Loop throught options # while getopts "$getopts_string" opt; do case $opt in h) usage;; :) die "Option -$OPTARG requires an argument.";; \?) die "Invalid option: -$OPTARG";; *) name="${varia[$opt]}" if [ "${!name}" == "false" ] ; then eval $name=true elif [ -n "$( declare -p "$name" 2>/dev/null | grep 'declare \-a')" ] ; then safe="${!name} $OPTARG" ; eval $name=\$safe else eval $name=\$OPTARG fi;; esac done ; shift $((OPTIND-1))