Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is mixing getopts with positional parameters possible?

I want to design a shell script as a wrapper for a couple of scripts. I would like to specify parameters for myshell.sh using getopts and pass the remaining parameters in the same order to the script specified.

If myshell.sh is executed like:

myshell.sh -h hostname -s test.sh -d waittime param1 param2 param3  myshell.sh param1 param2 -h hostname param3 -d waittime -s test.sh  myshell.sh param1 -h hostname -d waittime -s test.sh param2 param3 

All of the above should be able to call as

test.sh param1 param2 param3 

Is it possible to utilize the options parameters in the myshell.sh and post remaining parameters to underlying script?

like image 666
Bharat Sinha Avatar asked Jul 31 '12 14:07

Bharat Sinha


People also ask

Should I use getopt or getopts?

The main differences between getopts and getopt are as follows: getopt does not handle empty flag arguments well; getopts does. getopts is included in the Bourne shell and Bash; getopt needs to be installed separately. getopt allows for the parsing of long options ( --help instead of -h ); getopts does not.

Is getopts case sensitive?

Option letters are case sensitive.

What is a positional parameter determined by?

3.4. 1 Positional Parameters A positional parameter is a parameter denoted by one or more digits, other than the single digit 0 . Positional parameters are assigned from the shell's arguments when it is invoked, and may be reassigned using the set builtin command.

What is Optind in getopts?

According to man getopts , OPTIND is the index of the next argument to be processed (starting index is 1).


1 Answers

I wanted to do something similar to the OP, and I found the relevant information I required here and here

Essentially if you want to do something like:

script.sh [options] ARG1 ARG2 

Then get your options like this:

while getopts "h:u:p:d:" flag; do case "$flag" in     h) HOSTNAME=$OPTARG;;     u) USERNAME=$OPTARG;;     p) PASSWORD=$OPTARG;;     d) DATABASE=$OPTARG;; esac done 

And then you can get your positional arguments like this:

ARG1=${@:$OPTIND:1} ARG2=${@:$OPTIND+1:1} 

More information and details are available through the link above.

Hope that helps!!

like image 162
DRendar Avatar answered Oct 07 '22 13:10

DRendar