Question about getopts optional argument [args...]


 
Thread Tools Search this Thread
Top Forums UNIX for Beginners Questions & Answers Question about getopts optional argument [args...]
# 1  
Old 03-29-2019
Question about getopts optional argument [args...]

There are many places where I can see the syntax description for optargs, which, usually boils down to this:
Code:
getopts OPTSTRING VARNAME [ARGS...]
where:
OPTSTRING tells getopts which options to expect and where to expect arguments
VARNAME	tells getopts which shell-variable to use for option reporting
ARGS	tells getopts to parse these optional words instead of the positional parameters

None of the examples I've found show how to use the optional ARGS... variable length argument list. All examples focus on the positional arguments, which I know how to use.

I've tried several tests, but, the only effect of adding ARGS... to my script causes the positional arguments to be ignored ... nothing I've tried does anything with the optional arguments.

So, I'm curious ... can anyone give me a short example of how a variable length argument lists specified by ARGS... is used?

Thanks.

Also, please don't ask me to provide everything I've tried. They all fail, and, I'd rather cut to the chase with one simple example of what works.

Thanks,
sharkura
# 2  
Old 03-29-2019
Welcome to the forum.







Quote:
Originally Posted by sharkura
... the only effect of adding ARGS... to my script causes the positional arguments to be ignored
Which is as specified.


Quote:
... nothing I've tried does anything with the optional arguments.
Strange - appending a "line" of options should (and DOES!) make getopts evaluate those in lieu of the positional parameters, and it does for me. Pls (I know you dislike this) show an example of your failed attempts.




EDIT: Are you sure you did differentiate between the bash builtin getopts and the external command getopt?

Last edited by RudiC; 03-29-2019 at 11:48 AM..
This User Gave Thanks to RudiC For This Post:
# 3  
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..
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. 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

2. 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

3. 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

4. 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

5. 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

6. 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

7. 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

8. 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

9. 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

10. 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
Login or Register to Ask a Question