Getopts in bash

Bash is a powerful scripting language that allows developers to create complex automation scripts. One of the most important features of Bash is the ability to process command-line arguments. Command-line arguments are options or parameters passed to a script when it is executed. The getopts command is a built-in command in Bash that provides a simple way to process command-line arguments.

The getopts command is used to parse options and arguments passed to a script. It is a convenient way to implement command-line parsing, allowing developers to easily define and handle command-line arguments in their scripts.

The getopts command can be used to parse options and arguments passed to a script. An option is a letter or word that represents a command-line flag, while an argument is a value that is passed to a script. The getopts command can be used to process both options and arguments.

The basic syntax of the getopts command is as follows:

getopts optstring variable

The optstring parameter specifies the options that the script should accept. The options are specified as single characters, and can be followed by a colon (:) to indicate that they require an argument. The variable parameter specifies the name of the variable that will hold the currently processed option.

For example, the following script uses the getopts command to process the -f and -n options:

#!/bin/bash

while getopts ":fn:" opt; do
  case ${opt} in
    f )
      echo "Found -f option"
      ;;
    n )
      echo "Found -n option with argument ${OPTARG}"
      ;;
    \? )
      echo "Invalid option: ${OPTARG}"
      ;;
    : )
      echo "Option -${OPTARG} requires an argument."
      ;;
  esac
done

In this script, the optstring parameter is set to "fn:", which means that the script accepts the -f and -n options, with -n requiring an argument. The variable parameter is set to opt, which will hold the currently processed option.

The script uses a while loop to process each option in turn. The getopts command reads the next option from the command line and stores it in the opt variable. The case statement is then used to process the option.

If the option is -f, the script prints a message indicating that the -f option was found. If the option is -n, the script prints a message indicating that the -n option was found, along with the argument that was passed to it. If the option is invalid, the script prints an error message. If the option requires an argument but none was provided, the script prints an error message.

Did you find this article valuable?

Support The Revieww Company by becoming a sponsor. Any amount is appreciated!