getopts in bash scripting?getopts helps scripts read and handle command-line options (flags) easily and consistently.
It parses options like -a or -b value so your script can respond accordingly.
getopts?In the options string passed to getopts, add a colon : right after the option letter.
For example, getopts "a:b" means -a needs an argument, -b does not.
getopts use to store the current option letter?getopts stores the current option letter in the shell variable given as its second argument (typically named opt).
OPTARG holds the argument value for options that require one, while OPTIND tracks the next index to process.
OPTIND represent in getopts usage?OPTIND is the index of the next argument to be processed by getopts.
It starts at 1 and increments as options are parsed, helping your script know where options end and positional arguments begin.
getopts loop to handle options -a (no argument) and -b (requires argument).while getopts "ab:" opt; do
case $opt in
a) echo "Option a triggered" ;;
b) echo "Option b with value: $OPTARG" ;;
*) echo "Invalid option" ;;
esac
donegetopts, how do you indicate that an option requires an argument?Adding a colon ':' after the option letter tells getopts that this option needs an argument.
getopts?OPTARG stores the argument value for options that require one.
OPTIND represent in getopts?OPTIND tracks the next argument index to be processed by getopts.
getopts encounters an unknown option?getopts sets the option variable to '?' when it finds an invalid option.
getopts loop for options -x and -y with -y requiring an argument?Option y requires an argument, so it is followed by a colon ':' in the options string.
getopts to parse command-line options in a bash script.OPTARG and OPTIND when using getopts.