2014-12-12 60 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]ang:~$ ./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