Return to Snippet

Revision: 21719
at December 19, 2009 03:30 by syladmin


Initial Code
#!/bin/bash

# print the text embedded in the case that parse options from command line.
# the block is matched with the marker 'CommandParse' in comment, until 'esac'
extract_cmdl_options()
{
    # use vim for parsing:
    # 1st grep the case block and copy in register @p + unindent in the buffer of the file itself
    # 2nd filter lines which start with --opt or +opt and keep comment on hte following lines until an empty line
    # 3rd discard changes in the buffer and quit
    vim -n -es -c 'g/# CommandParse/+2,/^\s\+esac/-1 d p | % d | put p | %<' \
        -c 'g/^\([-+]\+[^)]\+\))/,/^\(\s\+[^- \t#]\|^$\)/-1 p' \
        -c 'q!' $0
}


# command line parsing {{{
arg_max=15
arg_endarg=0
# --------------------------------------------------
while [ $arg_endarg -eq 0 -a $# -gt 0 -a $arg_max -gt 0 ]
do
    arg_max=$(($arg_max - 1))

    # loop on each argument, if it's in the case modify the associated var
    # else end argument parsing and continue to the main routine

    # CommandeParse:
    case "$1" in
    --help)
        # This help message

        # print script header + the option desc
        # http://www.commandlinefu.com/commands/view/3344/display-an-embeded-help-message-from-bash-script-header
        sed -n -e '/^# Usage:/,/^$/ s/^# \?//p' < $0
        extract_cmdl_options
        exit
        ;;
    --some_option)
        echo "do something undocumented"
        ;;
    --etc)
        # nothing done
        ;;
    --exemple)
        # print more example, and exit
        cat /etc/motd
        exit
        ;;
    *)
        # stop parsing
        arg_endarg=1
        ;;
    esac
    if [ $arg_endarg -eq 0 ]
    then
        shift
    fi
done
# DONE parsing argument }}}

Initial URL

                                

Initial Description

                                

Initial Title
display embeded comments for every --opt, usefull for auto documenting your script

Initial Tags
Bash

Initial Language
Bash