getopts
shell programmingLinux/Unix
The getopts command is one of the most frequently used commands in Linux/Unix-like operating systems. getopts Parse command options in shell scripts
Quick Reference
Command Name:
getopts
Category:
shell programming
Platform:
Linux/Unix
Basic Usage:
getopts [options] [arguments]
Common Use Cases
Syntax
getopts optstring name [arg...]
Options
Parameter | Description |
---|---|
optstring |
A string containing the option characters to be recognized. If a character is followed by a colon, the option requires an argument. |
name |
A variable name that will be set to the found option character. |
arg |
Optional. If not provided, getopts processes the positional parameters of the shell. |
Special Variable | Description |
---|---|
OPTARG |
Contains the argument for options that require one. |
OPTIND |
The index of the next argument to be processed. Should be reset to 1 before using getopts in loops. |
OPTERR |
If set to 0, getopts suppresses error messages (default is 1). |
Examples
How to Use These Examples
The examples below show common ways to use the getopts
command. Try them in your terminal to see the results. You can copy any example by clicking on the code block.
# Basic Example
#!/bin/bash
while getopts "a:b:c" opt; do
case $opt in
a) echo "Option -a with argument: $OPTARG" ;;
b) echo "Option -b with argument: $OPTARG" ;;
c) echo "Option -c (flag, no argument)" ;;
\?) echo "Invalid option: -$OPTARG" >&2; exit 1 ;;
:) echo "Option -$OPTARG requires an argument." >&2; exit 1 ;;
esac
done
shift $((OPTIND-1))
echo "Remaining arguments: $@"