linux – 如何在bash结尾处使用不带参数的getopts选项

前端之家收集整理的这篇文章主要介绍了linux – 如何在bash结尾处使用不带参数的getopts选项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在bash中使用getopts.用户应该选择自己的选项.
大多数选项都有参数,但有两个选项没有参数.当没有参数的选项位于命令的中间时,它工作正常,但是当它在结尾时它不起作用.

注意 – 前两个参数(服务器和密码)是必需的,而不是getopts的一部分.

#!/bin/bash

SERVER=${1}
PASSWORD=${2}
VERSION=v0
ASKED_REVISION=0
DB=schema_1
PROPERTIES=1
FULL=0
USER=

# Usage info
show_help()
{
echo "
        Usage: Environment DBPassword [-V Version] [-R Revision] [-S Schema] [-P] [-F] [-U Username]

        -V Version      Version to deploy.
        -R Revision     Revision number (0 means the latest revision).
        -S Schema       Schema in the DB to deploy.
        -P              No(!) External Properties. If this flag is marked the deploy will not copy the external properties
        -F              Full deploy
        -U              Username. This User who run the deploy.

        For Example: ./deploy server1 123456 -V v1.0 -R 12345 -S schema1 -P -F -U User1

        -H              Help
"
}
OPTIND=3
while getopts ":V:R:S:P:F:U:H:" FLAG; do
  case "$FLAG" in
        V) # Set option "V" [Version]
                VERSION=$OPTARG
                ;;
        R) # Set option "R" [Revision]
                ASKED_REVISION=$OPTARG
                ;;
        S) # Set option "S" [Schema]
                DB=$OPTARG
                ;;
        P) # Set option "P" [No External Properties]
                PROPERTIES=0
                OPTIND=$OPTIND-1
                ;;
        F) # Set option "F" [FULL]
                FULL=1
                OPTIND=$OPTIND-1
                ;;


 U) # Set option "U" [User]
            USER=$OPTARG
            ;;
    H) # help
            show_help
            ;;
    \?)
            echo "Invalid option: -$OPTARG. Use -H flag for help."
            exit
            ;;
  esac
done

shift $((OPTIND-1))  #This tells getopts to move on to the next argument.

echo "Env=$SERVER"
echo "Pass=$PASSWORD"
echo "Version=$VERSION"
echo "Revision=$ASKED_REVISION"
echo "Schema=$DB"
echo "External Properties=$PROPERTIES"
echo "FULL=$FULL"
echo "USER=$USER"

-F和-P不应该得到一个参数.当我运行此命令时,它正常工作(中间的-F):

./deploy_test.sh server1 pass1234 -U 555 -R 55555 -F -V v1.0

当-F或-P在命令的末尾时,
这条线无法正常工作(一切正常,但-F):

./deploy_test.sh server1 pass1234 -U 555 -R 55555 -V v1.0 -F

解决方法

从不需要参数的选项中删除冒号,并且不要在while / case语句中自己手动执行任何移位或更改OPTIND(您仍需要在while循环之前设置OPTIND以跳过第一个2个论点):
while getopts ":V:R:S:PFU:H" FLAG; do

我已经显示了对于P和F选项以及H的适当更改的while行,因为它也不需要参数.

按照the documentation

if a character is followed by a colon,the option is expected to have an argument

所以:应该只有那些带参数的选项.

原文链接:https://www.f2er.com/linux/393080.html

猜你在找的Linux相关文章