Contents
Is the optarg the argument to the option?
If so, OPTARG is the argument to the option. Otherwise, OPTIND must be decremented by one. Of course, the option is now required to have an argument, meaning a character will be found when an option is missing an argument. Just use another case to determine if any options are required:
Do you need to copy optarg for later use?
It is one of the numerous flaws of the getopt documentation: it does not state clearly that optarg must be copied for later use (using strdup (), for instance) because it may be overwritten by later options or just plain freed by getopt. In the case of an ip and port you don’t need to store the strings.
Where to find optarg in Linux man pages?
optarg (3p) – Linux Man Pages. optarg: command option parsing. This manual page is part of the POSIX Programmer’s Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.
How to set optarg for Optional flags in Bash?
If getopts is silent, then a colon (‘:’) is placed in name and OPTARG is set to the option character found. The leading colon in the option string puts getopts into silent mode; it does not generate any error messages. The description doesn’t mention anything about optional option arguments. where the flag f ( -f) optionally accepts an argument.
Do you have to have an optional argument in getopts?
Any “optional” option arguments must actually be required as far as getopts will know. Of course, an optional argument must be a part of the same argument to the script as the option it goes with. Otherwise an option -f with an optional argument and an option -a with a required argument can get confused:
When to use the optind variable in getopts?
OPTIND is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, getopts places that argument into the variable OPTARG.