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: $@"
    # Usage Examples
    ./script.sh -a value1 -b value2 -c remaining args
    Process options with arguments and a flag.
    ./script.sh -ac -b value remaining args
    Process options with bundled flags. # Advanced Example Advanced #!/bin/bash usage() { echo "Usage: $0 [-h] [-v] [-f filename] [-n number] [arguments]" exit 1 } verbose=0 filename="" number=0 while getopts "hvf:n:" opt; do case $opt in h) usage ;; v) verbose=1 ;; f) filename="$OPTARG" ;; n) number="$OPTARG" ;; \?) usage ;; esac done shift $((OPTIND-1)) if [ $verbose -eq 1 ]; then echo "Verbose mode enabled" echo "Filename: $filename" echo "Number: $number" echo "Remaining args: $@" fi

    Try It Yourself

    Practice makes perfect! The best way to learn is by trying these examples on your own system with real files.

    Understanding Syntax

    Pay attention to the syntax coloring: commands, options, and file paths are highlighted differently.

    Notes

    The getopts command is a built-in utility in most POSIX-compliant shells (like bash, ksh, zsh) that helps parse command-line options and arguments in shell scripts. It provides a standardized way to handle options, making scripts more robust and user-friendly. Key features of getopts: 1. Option Parsing: getopts processes command-line arguments to identify options (usually prefixed with a hyphen) and their associated arguments. 2. Standard Compliance: It follows POSIX conventions for command-line syntax, supporting both single-character options and options that require arguments. 3. Error Handling: getopts can detect invalid options and missing required arguments, allowing scripts to handle these cases gracefully. 4. Option Bundling: It supports the common Unix convention of bundling multiple single-character options together (e.g., -abc instead of -a -b -c). 5. Automatic Variables: getopts sets special variables like OPTARG (for option arguments) and OPTIND (to track the current position in the argument list). 6. Loop Integration: Typically used in a while loop, getopts processes one option at a time, allowing for sequential option handling. 7. Shift Management: After processing options, scripts typically use the OPTIND variable to shift away processed options, leaving only non-option arguments. While getopts is more limited than the external getopt command (especially the GNU enhanced version), it has the advantage of being a shell built-in, making it more portable across Unix-like systems. It's particularly well-suited for scripts that need to handle simple to moderately complex option parsing needs while maintaining POSIX compatibility.

    Related Commands

    These commands are frequently used alongside getopts or serve similar purposes:

    Use Cases

    Learn By Doing

    The best way to learn Linux commands is by practicing. Try out these examples in your terminal to build muscle memory and understand how the getopts command works in different scenarios.

    $ getopts
    View All Commands