Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getopt shift optarg

Tags:

c

getopt

I need to call my program like this:

./program hello -r foo bar

I take hello out of argv[1], but i am having trouble with value bar, also should i change "r:" to something else?

while((c = getopt(argc, argv, "r:")) != -1){
   switch(i){
   ...
   case 'r':
     var_foo = optarg;
     //shell like argument shift here?
     var_bar = optarg;
     break;
...}

I know I could do this with passing through argv, but is there a way to do it with getopt similar way as in bash?

Thanks.

like image 606
rluks Avatar asked Apr 07 '12 21:04

rluks


People also ask

What does shift $(( Optind 1 )) do?

Thus shift $((OPTIND-1)) removes all the options that have been parsed by getopts from the parameters list, and so after that point, $1 will refer to the first non-option argument passed to the script.

Which is better 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.

What is getopt in shell?

Description. The getopts command is a Korn/POSIX Shell built-in command that retrieves options and option-arguments from a list of parameters. An option begins with a + (plus sign) or a - (minus sign) followed by a character. An option that does not begin with either a + or a - ends the OptionString.

What is ${ Optarg?

DESCRIPTION. The optarg, opterr, optind, and optopt variables are used by the getopt() function. optarg indicates an optional parameter to a command line option. opterr can be set to 0 to prevent getopt() from printing error messages.


1 Answers

bar is not an option argument in the eyes of getopt. Rather, GNU getopt rearranges the positional arguments so that at the end of the processing, you have argv[3] being "hello" and argv[4] being "bar". Basically, when you're done getopting, you still have positional arguments [optind, argc) to process:

int main(int argc, char * argv[])
{
     {
         int c;
         while ((c = getopt(argc, argv, ...)) != -1) { /* ... */ }
     }

     for (int i = optind; i != argc; ++i)
     {
         // have positional argument argv[i]
     }
}
like image 81
Kerrek SB Avatar answered Oct 22 '22 13:10

Kerrek SB