getopts第二个标志不是必需的?

时间:2014-12-12 23:48:29

标签: bash getopts

确保-v-o都是必需元素但-h不在我的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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这个怎么样?:

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

test=$(echo "$@" | grep "\-v" | grep "\-o")

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

输出:

bob@crunchbang:~$ ./test -v 5.0 -h
requirements not met.
Usage: ./test [-v <5.x|6.x>] [-o <string>]
bob@crunchbang:~$ ./test -v 5.0
requirements not met.
Usage: ./test [-v <5.x|6.x>] [-o <string>]
bob@crunchbang:~$ ./test -o "yoh"
requirements not met.
Usage: ./test [-v <5.x|6.x>] [-o <string>]
bob@crunchbang:~$ ./test 
requirements not met.
Usage: ./test [-v <5.x|6.x>] [-o <string>]
相关问题