How to use getopts parameter without argument at the end in bash

I want to use getopts in bash. The user must select their own parameters. most parameters take arguments, but there are two parameters that have no argument. It works well when an option with no argument is in the middle of the command, but when it ends, it does not work.

Note. The first two arguments (Server and Password) are required, not part of 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 and -P should not accept an argument. When I run this command, it works correctly (-F in the middle):

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

When -F or -P is at the end of the command, this line does not work correctly (everything works fine, but -F):

 ./deploy_test.sh server1 pass1234 -U 555 -R 55555 -V v1.0 -F 
+5
source share
1 answer

Remove the colons from parameters that require no arguments, and do not manually make any changes or change OPTIND yourself in the while / case status (you still need to set OPTIND before the while loop to skip the first 2 arguments):

 while getopts ":V:R:S:PFU:H" FLAG; do 

I showed the while line with the corresponding changes for the parameters P and F , as well as for H , since this also does not require an argument.

According to the documentation :

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

So : should only be present for options with arguments.

+6
source

Source: https://habr.com/ru/post/1239295/


All Articles