简体   繁体   English

getopts用于标志和选项解析

[英]getopts to use for both flags and option parsing

I am using getopts in my script and I want to work it for all the following order of option parsing. 我在脚本中使用了getopts,并且希望将其用于以下所有选项解析顺序。

./myscript -c server
./myscript -c -h server
./myscript server -c
./myscript -h server -c
./myscript server

I am using myscript as follows. 我正在使用myscript如下。

#!/bin/bash
while getopts c:h: var
do
case $var in 
h) host=$OPTARG;;
c) FLAG=1
esac
done

Here "server" is a argument and should load even -h option specifies or not and also -c option I am using for a FLAG.Is there a way to get this achieved. 这里的“服务器”是一个参数,甚至应该加载-h选项是否指定以及我正在为FLAG使用的-c选项。有没有办法实现这一目标。

Sometimes it's better not to use getopts at all: 有时最好不要使用getopts

#!/bin/bash

while [[ $# -gt 0 ]]; do
    case "$1" in
    -c)
        FLAG=1
        ;;
    -h)
        HOST=$2
        shift
        ;;
    -*)
        echo "Unknown option: $1"
        exit 1
        ;;
    *)
        HOST=$1
        ;;
    esac
    shift
done

By the way your script would give you a syntax error since you missed the two semicolons: 顺便说一句,由于您错过了两个分号,因此脚本会给您带来语法错误:

c) FLAG=1 ;;

I fixed my issue by applying some extra validations.. 我通过应用一些额外的验证解决了我的问题。

#!/bin/bash

USAGE() {
        echo "Invalid Option"
        exit 1
}

if [ $# -eq 2 ]; then
                case $1 in
                        -c) FLAG=1; host=$2 ;;
                        -h) host=$2 ;;
                esac
                if [ -z "$host" ]; then
                case $2 in
                        -c) FLAG=1; host=$1;;
                        -h) host=$1;;
                        *) USAGE;;
                esac
                fi
        else

        while getopts q:c:h: OPTION
        do
            case ${OPTION} in
                q) USAGE;;
                h) host=$OPTARG;;
                c) FLAG=1 ;;
                *)USAGE;;
            esac
        done
fi

if [ $# -eq 1 ]; then host=$1 ;fi

echo Host = $host FLag = $FLAG

In all the cases I am getting my host in my script as shown in this output. 在所有情况下,如输出所示,我都在脚本中获取主机。

$ ./myscript.sh server1
Host = server1 FLag =
$ ./myscript.sh -c server1
Host = server1 FLag = 1
$ ./myscript.sh server1 -c
Host = server1 FLag = 1
$ ./myscript.sh server1 -h
Host = server1 FLag =
$ ./myscript.sh -h server1
Host = server1 FLag =

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM