0
0
Bash Scriptingscripting~5 mins

Option parsing with getopts in Bash Scripting

Choose your learning style9 modes available
Introduction
Option parsing with getopts helps your script understand and handle user inputs like flags and options easily.
When your script needs to accept options like -h for help or -f for a file name.
When you want to make your script flexible by allowing users to customize its behavior.
When you want to check if required options are given before running the main task.
When you want to provide clear error messages if users give wrong options.
When you want to support both options with and without arguments.
Syntax
Bash Scripting
getopts optstring variable

# optstring: string of option letters. A letter followed by : means that option needs an argument.
# variable: name of the variable to store the current option letter.
getopts processes options one by one from the command line arguments.
Use a while loop with getopts to handle multiple options.
Examples
This example handles -h (no argument) and -f (requires an argument).
Bash Scripting
while getopts "hf:" opt; do
  case $opt in
    h) echo "Help option selected" ;;
    f) echo "File option with argument: $OPTARG" ;;
    *) echo "Invalid option" ;;
  esac
done
Option 'a' requires an argument, 'b' does not.
Bash Scripting
while getopts "a:b" opt; do
  case $opt in
    a) echo "Option a with argument: $OPTARG" ;;
    b) echo "Option b selected" ;;
  esac
done
Sample Program
This script accepts -h for help, -u with a username argument, and -f with a filename argument. It prints what it receives.
Bash Scripting
#!/bin/bash

while getopts "hu:f:" opt; do
  case $opt in
    h)
      echo "Usage: $0 [-h] [-u username] [-f filename]"
      exit 0
      ;;
    u)
      echo "Username set to: $OPTARG"
      ;;
    f)
      echo "Filename set to: $OPTARG"
      ;;
    *)
      echo "Invalid option: -$opt" >&2
      exit 1
      ;;
  esac
done
OutputSuccess
Important Notes
Always quote "$OPTARG" when using it to avoid word splitting issues.
getopts only parses options starting with a dash (-).
After getopts finishes, use shift $((OPTIND -1)) to move past parsed options if you want to handle other arguments.
Summary
getopts helps scripts read options and their arguments easily.
Use a while loop and case statement to handle each option.
Options followed by : in optstring require an argument.