getopts Command in Linux with Examples
Last Updated :
03 Jul, 2024
The getopts is a very convenient bash script utility command. It helps us to conveniently and gracefully handle the passing of flags(short version), and arguments in a clean, standardized manner. Instead of having the developer manually handle the flags passed to a script, this provides a handy way of handling this when iterating through a while loop. In this article, we will discuss what getopts is, its syntax explain its options, make it better usage of getopts with examples, and then explain its importance, best practices, and use cases.
What is a getopts Command?
The `getopts` is a available command in Unix and Linux environments that is used for parsing command-line options in shell scripts. It allows the scripts to handle flags (options) and arguments that are passed by users when executing the script. By using `getopts`, shell scripts can efficiently process and validate input, improving their usability and functionality in automation tasks and system administration.
Syntax
getopts optstring name [arg]

Options of getopts
The following are the options of getopts:
Option | Description |
---|
-o | It specifies a list of single-character options that to be parsed. |
-a | It appends the options to the option string defined by -o . |
-n | It specifies the name of the variable to store the next option. |
-q | It ignorize the error messages from getopts . |
-s | It sets the variable OPTARG to the option's argument. |
-u | It will unsets the option list and allows the getopts to be reused. |
Examples and Usage of getopts command
The following are the examples and usage of getopts command:
1. Printing the help section: Enter the following command to print the help section of the getopts command.
getopts --help
- The above command will print the details of the command along with some parameters and options that could be used to run the command.

2. Usage in a script: getopts could be used in a script in Linux as well. The following script depicts the same.
#!/bin/bash
while getopts ":a:bc:" flag;do
echo "flag -$flag, Argument $OPTARG";
done
This script runs a while loop, which iterates through the arguments that match with given optstring, in this case, "a:bc:", and stores the value of the flag in the variable flag. If the flag had any associated argument, it is stored in a variable OPTARG.
The optstring works in the following way:
- For every option letter, getopts stores the option in the variable flag(declared just after the optstring), and iterates the loop.
- Every option letter followed by a colon expects an argument, which is stored in the variable OPTARG.
- If getopts was expecting an argument, but could not parse one, it prints an error. If it was not expecting one, OPTARG will be initialized to ""(an empty string).
- If the very first character of the optstring was ":"(a colon), the error message is not printed
3. Running the script by passing the arguments as expected.
./getoptsDemo.sh -a argA -b

Note: OPTARG for -b is blank, and not its previous value since it is initialized for every iteration. Also, -c is not passed, which is not an issue, as each flag in optstring is optional.
4. Running the script by skipping the parameter for a flag where it is required: This prints an error message. The flag is initialized to "?", and OPTARG is ".
./getoptsDemo.sh -a

5. Running the script by adding a flag not present in the optstring: This prints an error message. Again, the flag is initialized to "?", and OPTARG is "".
./getoptsDemo.sh -d

- If the first character was ":", getopts goes into silent mode, the error messages are not printed, and the behavior changes in some cases. Consider the optstring ":a" for the following example:-
6. Skipping the parameter for a flag where it is required: The flag is initialized to ":", and OPTARG is set to the option character.
./getoptsDemo.sh -a

Difference between getopts and getopt
The following are the difference beteween getopts and getopt:
Feature | getopts | getopt |
---|
Type | It is a shell built-in command (bash, ksh) | It is a external command/utility (typically C-based) |
Usage | It parses the short options (single characters) | It will parses both short options (single characters) and long options (--option) |
Support | It is limited to POSIX-compliant short options | It supports both short and long options, offering greater flexibility |
Availability | It is available as a built-in in most POSIX-compliant shells (bash, ksh) | It founded as a separate command/utility on Unix-like systems |
Complexity | It simplifies the syntax and usage within shell scripts | It requires more setup and handling due to being an external utility |
Importance of getopts
The following are the importance of getopts command:
- Efficient Option Parsing: It helps in simplifying the handling of command line options and arguments, allowing the scripts to praise the user input reliably and efficiently.
- Standarized Input handling: It supports to POSIX standards with ensuring the compatibility across different unix and linux systems.
- Error Handling: The getopts provides the built in mechanism for error reporting and validation. It helps in scripting to gracefully handle the incorrect or unexpected user input.
- Enhanced Script Usability: It provides the structured handling of option and arguments improving the usability and clarity of shell scripts.
Best practices of using getopts
The following are the best practices of using getopts:
- Define Options Clearly: On defining the list of options clearly ( -o ), your scripts will accept. Try to use single character options for simplicity and consistency with UNIX environments.
- Handle Arguements Properly: Try to use -s to set the OPTARG which captures the arugemnet that are associated with an option. It helps in validating and processing the arguments accordingly to ensure correct functionality.
- Error Handling: On utilizing the -q, we can suppress the default error messages and can implement the custom error handling.
- Optimization: By structuring your script we can minimize the number of getopts calls and can efficiently process the options and arguements.
Usecases of getopts command
The following are the some of the key usecases of getopts command in linux:
- Option Parsing: with this command we can enable the scripts to parse and react to command-line options (flags) like
-h
for help or -v
for verbose output. - Argument Handling: It comes with facilitating the validation and processing of arguments that are passed to a script, ensuring correct execution based on user input.
- Interactive Scripting: It supports interactive shell scripts by validating user input for options and arguments, enhancing script functionality and usability.
- Standardization: It enhances the script usability by supporting to standard command-line interface conventions, making scripts more intuitive and easier to integrate into automation workflows.
Similar Reads
getent command in Linux with examples The 'getent' command in Linux is a powerful tool that allows users to access entries from various important text files or databases managed by the Name Service Switch (NSS) library. This command is widely used for retrieving user and group information, among other data, stored in databases such as '
5 min read
gs command in Linux with Examples gs command invokes Ghostscript, which is an interpreter of Adobe Systems PostScript and Portable Document Format(PDF) languages. After executing Ghostscript it reads further input from the standard input stream until it encounters 'quit' command. Syntax: gs [ options ] [ files ] ... Options: Below a
2 min read
htop command in Linux with examples htop command in Linux system is a command line utility that allows the user to interactively monitor the systemâs vital resources or serverâs processes in real-time. htop is a newer program compared to top command, and it offers many improvements over top command. htop supports mouse operation, uses
4 min read
help Command in Linux with examples If youâre new to the Linux operating system and struggling with command-line utilities, the help command is one of the first tools you should learn. As its name suggests, the 'help' command provides detailed information about built-in shell commands, making it an essential resource for beginners and
5 min read
expr command in Linux with examples The expr command in Unix is a versatile tool used for evaluating expressions in the shell environment. It performs a wide range of functions, including arithmetic calculations, string operations, and comparisons based on regular expressions.What is the 'expr' Command?expr stands for "expression" and
3 min read