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.
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.
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.
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.
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.
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]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With