Bash getopts: reading $OPTARG for optional flags? -


i'd able accept both mandatory , optional flags in script. here's have far.

#!bin/bash  while getopts ":a:b:cdef" opt;       case $opt in         ) apple="$optarg";;         b ) banana="$optarg";;         c ) cherry="$optarg";;         d ) dfruit="$optarg";;         e ) eggplant="$optarg";;         f ) fig="$optarg";;         \?) echo "invalid option: -"$optarg"" >&2             exit 1;;         : ) echo "option -"$optarg" requires argument." >&2             exit 1;;       esac     done echo "apple "$apple"" echo "banana "$banana"" echo "cherry "$cherry"" echo "dfruit "$dfruit"" echo "eggplant "$eggplant"" echo "fig "$fig"" 

however, output following:

bash script.sh -a apple -b banana -c cherry -d dfruit -e eggplant -f fig 

...outputs this:

apple apple banana banana cherry  dfruit  eggplant  fig 

as can see, optional flags not pulling arguments $optarg required flags. there way read $optarg on optional flags without getting rid of neat ":)" error handling?

=======================================

edit: wound following advice of gilbert below. here's did:

#!/bin/bash    if [[ "$1" =~ ^((-{1,2})([hh]$|[hh][ee][ll][pp])|)$ ]];     print_usage; exit 1   else     while [[ $# -gt 0 ]];       opt="$1"       shift;       current_arg="$1"       if [[ "$current_arg" =~ ^-{1,2}.* ]];         echo "warning: may have left argument blank. double check command."        fi       case "$opt" in         "-a"|"--apple"      ) apple="$1"; shift;;         "-b"|"--banana"     ) banana="$1"; shift;;         "-c"|"--cherry"     ) cherry="$1"; shift;;         "-d"|"--dfruit"     ) dfruit="$1"; shift;;         "-e"|"--eggplant"   ) eggplant="$1"; shift;;         "-f"|"--fig"        ) fig="$1"; shift;;         *                   ) echo "error: invalid option: \""$opt"\"" >&2                               exit 1;;       esac     done   fi    if [[ "$apple" == "" || "$banana" == "" ]];     echo "error: options -a , -b require arguments." >&2     exit 1   fi 

thanks much, everyone. works far.

most shell getopts have been annoying me long time, including lack of support of optional arguments.

but if willing use "--posix" style arguments, visit bash argument case args in $@


Comments

Popular posts from this blog

Line ending issue with Mercurial or Visual Studio -

java - Jtable duplicate Rows -

java - Run a .jar on Heroku -