Getting Options in Bash

In Bash, you can process command-line options, also known as flags or switches, using the getopts built-in command. The getopts command provides a convenient way to parse and handle options passed to a script.

Here’s a basic example of using getopts to process options:

#!/bin/bash

while getopts ":a:b:c" opt; do
  case $opt in
    a)
      echo "Option -a was provided with argument: $OPTARG"
      ;;
    b)
      echo "Option -b was provided with argument: $OPTARG"
      ;;
    c)
      echo "Option -c was provided"
      ;;
    \?)
      echo "Invalid option: -$OPTARG"
      ;;
  esac
done

In this example, the getopts command is used within a while loop to iterate over the options provided. The : after each option letter indicates that the option can accept an argument.

Inside the case statement, each option is handled based on its corresponding action. The OPTARG variable contains the argument associated with an option that requires one.

You can run the script and provide options with their arguments when invoking it:

./my_script.sh -a argumentA -b argumentB -c

The script will process each option and perform the corresponding actions. In the example above, it will display messages indicating which options were provided and their associated arguments.

If an invalid option is provided, the ? case will be triggered, displaying an error message.

You can customize the options and actions according to your script’s requirements by modifying the case statement inside the getopts loop.

The getopts command provides a flexible and standard way to handle command-line options in Bash, allowing you to create scripts that support various flags and arguments.

Leave a Comment

Your email address will not be published. Required fields are marked *