Sponsored Content
Top Forums UNIX for Beginners Questions & Answers Question about getopts optional argument [args...] Post 303033124 by drl on Saturday 30th of March 2019 11:49:35 AM
Old 03-30-2019
Hi.

Here are the guts of a test script, "s0", which calls helper scripts "s1" and "s2", using getopt and getopts, adapted from A small example on Bash getopts. #bash #getopt #getopts . GitHub, which in turn, was one of the top results of a Google search for keywords short example of getopt and getopts:
Code:
# Utility functions: print-as-echo, print-line-with-visual-space.
pe() { for _i;do printf "%s" "$_i";done; printf "\n"; }
pl() { pe;pe "-----" ;pe "$*"; }

pl " Results, getopt, s1 -a mystuff x y z:"
./s1 -a mystuff x y z

pl " Results, getopts, s2 -a mystuff x y z:"
./s2 -a mystuff x y z

pl " Code for s1 and s2:"
pe
head -50 s1 s2

producing:
Code:
$ ./s0

Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 3.16.0-7-amd64, x86_64
Distribution        : Debian 8.11 (jessie) 
bash GNU bash 4.3.30

-----
 Results, getopt, s1 -a mystuff x y z:
Got option 'a' with argument 'mystuff'
Remaining args are: <'x' 'y' 'z'>

-----
 Results, getopts, s2 -a mystuff x y z:
Got option 'a' with argument mystuff
Remaining args are: <x y z>

-----
 Code for s1 and s2:

==> s1 <==
#!/bin/bash

#
# Example using getopt (vs builtin getopts) that can also handle long options.
# Another clean example can be found at:
# http://www.bahmanm.com/blogs/command-line-options-how-to-parse-in-bash-using-getopt
#

aflag=n
bflag=n
cargument=

# Parse options. Note that options may be followed by one colon to indicate
# they have a required argument
if ! options=$(getopt -o a:bc: -l along,blong,clong: -- "$@")
then
  # Error, getopt will put out a message for us
  exit 1
fi

set -- $options

while [ $# -gt 0 ]
do
  # Consume next (1st) argument
  case $1 in
    -b|--blong)
    bflag="y" ;;
    # Options with required arguments, an additional shift is required
    -a|--along)
      aargument="$2" ; shift
      echo "Got option 'a' with argument ${aargument}"
    aflag="y" ;;
    -c|--clong)
    cargument="$2" ; shift;;
    (--)
  shift; break;;
  (-*)
echo "$0: error - unrecognized option $1" 1>&2; exit 1;;
(*)
break;;
esac
  # Fetch next argument as 1st
  shift
done

shift $((OPTIND-1))

echo "Remaining args are: <${@}>"

==> s2 <==
#!/bin/bash

while getopts ":da:" opt; do
  case $opt in
    d)
      echo "Entering DEBUG mode"
    ;;
    a)
      echo "Got option 'a' with argument ${OPTARG}"
    ;;
    :)
      echo "Error: option ${OPTARG} requires an argument"
    ;;
    ?)
      echo "Invalid option: ${OPTARG}"
    ;;
  esac
done

shift $((OPTIND-1))

echo "Remaining args are: <${@}>"

You can then test these yourself as required.

Best wishes ... cheers, drl

Last edited by drl; 03-30-2019 at 01:09 PM..
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

getopts and "priority level" for args

Hi, I use getopts in this way:while getopts ":d:f:crapv" Option do case $Option in d ) BACKUP_DIR="$OPTARG";echo $BACKUP_DIR;; #echo fot test c ) compress_file;; r ) remove_file;; a ) remove_file && compress_file;;... (2 Replies)
Discussion started by: mbarberis
2 Replies

2. Shell Programming and Scripting

getopts and a list argument

Hi, I'm using bash and ksh93 compatible derivatives. In a recent getopts experience, I found myself spending far too much time on this little problem. I hope someone can help... So here's the deal. I want to build have a command line interface that accepts either zero, one, or... (4 Replies)
Discussion started by: duderonomy
4 Replies

3. Shell Programming and Scripting

getopts ... only allow a single instance of an argument?

Hi there, if i have a simple getopts like below ...how can i make it so that if somebody enters more than one -g argument for example, it will error with a " you cannot enter more than one -g" or something like that.? I want to only allow one instance of a -g or a -h etc .. while getopts... (1 Reply)
Discussion started by: hcclnoodles
1 Replies

4. Programming

Optional non-const reference argument c++ ?

Is it possible to have a non-const reference variable as an OPTIONAL/DEFAULT parameter to c++ function ex void read(string &data,int &type=0 /*or something*/) ; so i will call read(data); //or int type; read(data,type); printf("Type =%d",type); I found one dirty workaround ... (2 Replies)
Discussion started by: johnbach
2 Replies

5. Shell Programming and Scripting

getopts : two values to a single argument ?

Hi Gurus I am trying to figure out (with not much success) how to pass two values to a single getopts argument ... for example ./script -a Tuesday sausagesThe $OPTARG variable seems to only get populated with the first argument. What im looking to do is to process the first argument (i.e.make... (6 Replies)
Discussion started by: rethink
6 Replies

6. Shell Programming and Scripting

getopts - optional and problem to display help

In the below code while getopts :rfw:d:s:a: options do case "$options" in r) echo reverse;; f) echo forward;; w) window=$OPTARG;; d) duration=$OPTARG;; s) search=$OPTARG;; a) value=$OPTARG;; *) help; exit;; esac done ... (2 Replies)
Discussion started by: Amutha
2 Replies

7. Shell Programming and Scripting

Getopts how to handle missing '-' in command line args.

I'm using getopts to process command line args in a Bash script. The code looks like this: while getopts ":cfmvhs:t:" option; do case $option in c) operationMode="CHECK" ;; f) operationMode="FAST" ;; m) ... (6 Replies)
Discussion started by: gencon
6 Replies

8. Shell Programming and Scripting

Getopts - space in argument (OPTARG)

Hi, I want to capture space as well from the argument eg: script.ksh -m "Message from xyz" -e "email@xyz.com" script.ksh -m 'Message from xyz' -e 'email@xyz.com' I am parsing using getopts, but for option "m" OPTARG is returning only "Message". Please use code tags next time for... (9 Replies)
Discussion started by: tostay2003
9 Replies

9. Shell Programming and Scripting

ksh - default value for getopts option's argument

Hello everyone, I need help in understanding the default value for getopts option's argument in ksh. I've written a short test script: #!/bin/ksh usage(){ printf "Usage: -v and -m are mandatory\n\n" } while getopts ":v#m:" opt; do case $opt in v) version="$OPTARG";; ... (1 Reply)
Discussion started by: da1
1 Replies

10. Shell Programming and Scripting

Getopts with optional parameters

Hi Unix Gurus, i am on learning path of unix, and yet to discover many things. I came across with this requirement where i need to pass parameters but the position of parameters is not fixed so after doing some google search got to know "getopts" can handle that. So here is my code: function... (3 Replies)
Discussion started by: gnnsprapa
3 Replies
getoptcvt(1)                                                       User Commands                                                      getoptcvt(1)

NAME
getoptcvt - convert to getopts to parse command options SYNOPSIS
/usr/lib/getoptcvt [-b] filename /usr/lib/getoptcvt DESCRIPTION
/usr/lib/getoptcvt reads the shell script in filename, converts it to use getopts instead of getopt, and writes the results on the standard output. getopts is a built-in Bourne shell command used to parse positional parameters and to check for valid options. See sh(1). It supports all applicable rules of the command syntax standard (see Rules 3-10, intro(1)). It should be used in place of the getopt command. (See the NOTES section below.) The syntax for the shell's built-in getopts command is: getopts optstring name [ argument...] optstring must contain the option letters the command using getopts will recognize; if a letter is followed by a colon (:), the option is expected to have an argument, or group of arguments, which must be separated from it by white space. Each time it is invoked, getopts places the next option in the shell variable name and the index of the next argument to be processed in the shell variable OPTIND. Whenever the shell or a shell script is invoked, OPTIND is initialized to 1. When an option requires an option-argument, getopts places it in the shell variable OPTARG. If an illegal option is encountered, ? will be placed in name. When the end of options is encountered, getopts exits with a non-zero exit status. The special option -- may be used to delimit the end of the options. By default, getopts parses the positional parameters. If extra arguments (argument ...) are given on the getopts command line, getopts parses them instead. So that all new commands will adhere to the command syntax standard described in intro(1), they should use getopts or getopt to parse posi- tional parameters and check for options that are valid for that command (see the NOTES section below). OPTIONS
The following option is supported: -b Makes the converted script portable to earlier releases of the UNIX system. /usr/lib/getoptcvt modifies the shell script in file- name so that when the resulting shell script is executed, it determines at run time whether to invoke getopts or getopt. EXAMPLES
Example 1: Processing the arguments for a command The following fragment of a shell program shows how one might process the arguments for a command that can take the options -a or -b, as well as the option -o, which requires an option-argument: while getopts abo: c do case $c in a | b) FLAG=$c;; o) OARG=$OPTARG;; ?) echo $USAGE exit 2;; esac done shift `expr $OPTIND - 1` Example 2: Equivalent code expressions This code accepts any of the following as equivalent: cmd -a -b -o "xxx z yy" filename cmd -a -b -o "xxx z yy" -filename cmd -ab -o xxx,z,yy filename cmd -ab -o "xxx z yy" filename cmd -o xxx,z,yy b a filename ENVIRONMENT VARIABLES
See environ(5) for descriptions of the following environment variables that affect the execution of getopts: LC_CTYPE, LC_MESSAGES, and NLSPATH. OPTIND This variable is used by getoptcvt as the index of the next argument to be processed. OPTARG This variable is used by getoptcvt to store the argument if an option is using arguments. EXIT STATUS
The following exit values are returned: 0 An option, specified or unspecified by optstring, was found. >0 The end of options was encountered or an error occurred. ATTRIBUTES
See attributes(5) for descriptions of the following attributes: +-----------------------------+-----------------------------+ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | +-----------------------------+-----------------------------+ |Availability |SUNWcsu | +-----------------------------+-----------------------------+ |CSI |enabled | +-----------------------------+-----------------------------+ SEE ALSO
intro(1), getopts(1), sh(1), shell_builtins(1), getopt(3C), attributes(5) DIAGNOSTICS
getopts prints an error message on the standard error when it encounters an option letter not included in optstring. NOTES
Although the following command syntax rule (see intro(1)) relaxations are permitted under the current implementation, they should not be used because they may not be supported in future releases of the system. As in the EXAMPLES section above, -a and -b are options, and the option -o requires an option-argument. The following example violates Rule 5: options with option-arguments must not be grouped with other options: example% cmd -aboxxx filename The following example violates Rule 6: there must be white space after an option that takes an option-argument: example% cmd -ab oxxx filename Changing the value of the shell variable OPTIND or parsing different sets of arguments may lead to unexpected results. SunOS 5.10 7 Jan 2000 getoptcvt(1)
All times are GMT -4. The time now is 09:11 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy