Search code examples
bashshellgetoptgetopt-longgetopts

working with options in bash code


Possible Duplicate:
Using getopts in bash shell script to get long and short command line options

I'm trying to figure out how to make use of flag like -e/--email -h/--help for example.

UPDATE: Current example:

while getopts ":ec:h" OptionArgument; do
case $OptionArgument in

        e ) S1=${OPTARG};;
        c ) S2=${OPTARG};;
        h ) usage;;
        \?) usage;;
        * ) usage;;
esac
done

However, if I leave blank it does nothing. If I add an -h it still runs and will not show usage.

UPDATE2

while [ $1 ]; do
        case $1 in
                '-h' | '--help' | '?' )
                        usage
                        exit
                        ;;
                '--conf' | '-c' )

                        ;;
                '--email' | '-e' )
                        EMAIL=$1
                        ;;
                * )
                        usage
                        exit
                        ;;
        esac
        shift
done

-h/--help works but everything else fails and displays usage.


Solution

  • If you want long GNU like options and short ones, see this script to source in your script http://stchaz.free.fr/getopts_long.sh and an example :

    Example :

    #!/bin/bash
    # ( long_option ) 0 or no_argument,
    # 1 or required_argument, 2 or optional_argument).
    
    Help() {
    cat<<HELP
    Usage :
        $0 [ --install-modules <liste des modules> ] [-h|--help]
    HELP
        exit 0
    }
    
    . /PATH/TO/getopts_long.sh
    
    OPTLIND=1
    while getopts_long :h opt \
        install-modules 1 \
        help 0 "" "$@"
    do
        case "$opt" in
            install-modules)
                echo $OPTLARG
            ;;
            h|help)
                Help; exit 0
            ;;
            :)
               printf >&2 '%s: %s\n' "${0##*/}" "$OPTLERR"
               Help
               exit 1
            ;;
        esac
    done
    shift "$(($OPTLIND - 1))"