How do I write a command help in Shell script (bash)?
Mainly the strategy is: 1. Create a printUsage function. 2. Use getopt to verify the parameters that need arguments. 3. With getopt switch the list of parameter. Here is a brief example: ############--1--################## function printUsage { echo "One line description of the command" echo "" echo "Usage: `basename $0` [ANY_MANDATORY_ARGUMENTS] [OPTIONS] " echo "Options: " echo " -o | -option OPT_ARGUMENT description of the option and its argument" echo " -a | -another description of the option" echo " -h | -help prints this help and exits" } ############--2--################## export POSIXLY_CORRECT=1 #this are the options, when the options need an argument, the : is placed next to the option $LONGOPTS=option:,another,help $SHORTOPTS=o:ah getopt -n `basename $0` -Q -u -a -l $LONGOPTS $SHORTOPTS "$@" || { printUsage exit 1; } ############--3--################## set -- `getopt -u -a -l $LONGOPTS $SHORTOPTS "$@"` while : do case "$1" in --option) CL_OPTION=$2 ; shift ;; -o) CL_OPTION=$2 ; shift ;; --another) CL_ANOTHER=true ;; --a) CL_ANOTHER=true ;; --help) CL_HELP=true ;; -h) CL_HELP=true ;; --) break ;; esac shift done shift # # (Note: Rest of command line now in $@ ) # # restore export POSIXLY_CORRECT= unset POSIXLY_CORRECT if [ "$CL_HELP" ] ; then printUsage exit 1 fi ############################## Things to consider when using 'getopt': * If the script needs an argument of the form: "a string with spaces", getopt interpret the argument as "a", discarding the rest of the string. For that kind of cases, is useful to use getopts, although the use is diferent from the example above. Also, getopts doesn't accept option like words, just letters. -- CarlitaParedes - 27 Jun 2006 |
Related articles appear here based on the labels you select. Click to edit the macro and add or change labels.
|