2014-12-12 5 views
0

Имея проблемы, удостоверяясь, что оба значения -v и -o являются обязательными элементами, но -h не в моих getopts. как бы я это исправить?getopts второй флаг не требуется?

usage() { echo "Usage: $0 [-v <5.x|6.x>] [-o <string>]" 1>&2; exit 1; } 

if (! getopts ":v:o:h" opt); then 
    echo "Usage: `basename $0` options (-v [version]) (-o [organization unit]) -h for help"; 
    exit $E_OPTERROR; 
fi 

while getopts ":v:o:h" opt; do 
    case $opt in 
     v) vermajor=$OPTARG;; 
     o) org_unit=$OPTARG;; 
     h) usage;; 
     \?) echo "Invalid option: -$OPTARG" >&2; exit 1;; 
     :) echo "Option -$OPTARG requires an argument." >&2; exit 1;; 
    esac 
done 

exit 

ответ

0

Что об этом ?:

usage() { echo "Usage: $0 [-v <5.x|6.x>] [-o <string>]" 1>&2; exit 1; } 

test=$(echo "[email protected]" | grep "\-v" | grep "\-o") 

if [[ -z "$test" ]]; then 
    printf "requirements not met.\n" 
    usage 
fi 
if [[ -n "$test" ]]; then 
    printf "requirements met.\n" 
fi 

Выход:

[email protected]:~$ ./test -v 5.0 -h 
requirements not met. 
Usage: ./test [-v <5.x|6.x>] [-o <string>] 
[email protected]:~$ ./test -v 5.0 
requirements not met. 
Usage: ./test [-v <5.x|6.x>] [-o <string>] 
[email protected]:~$ ./test -o "yoh" 
requirements not met. 
Usage: ./test [-v <5.x|6.x>] [-o <string>] 
[email protected]:~$ ./test 
requirements not met. 
Usage: ./test [-v <5.x|6.x>] [-o <string>] 
0

Законченное с этим

usage() { echo "Usage: $0 [-v <5.x|6.x>] [-o <string>]" 1>&2; exit 1; } 

if [[ "$1" =~ "^((-{1,2})([Hh]$|[Hh][Ee][Ll][Pp])|)$" ]]; then 
    usage 
else 
    while [[ $# -gt 0 ]]; do 
     opt="$1"; shift 
     current_arg="$1" 

     if [[ "$current_arg" =~ ^-{1,2}.* ]]; then 
      echo "==> WARNING: You may have left an argument blank. Double check your command." 
     fi 

     case "$opt" in 
      "-v"|"--version" ) vermajor="$1"; shift;; 
      "-o"|"--org"  ) org_unit="$1"; shift;; 
      *     ) echo "==> ERROR: Invalid option: \""$opt"\"" >&2 
            exit 1;; 
     esac 
    done 
fi 

if [[ "$vermajor" == "" || "$org_unit" == "" ]]; then 
    echo "ERROR: Options -v and -o require arguments." >&2; exit 1 
fi 

exit