← Back to Bash Course | Chapter 12: Error Handling & Debugging | Lesson 7 of 12

Script Arguments with getopts

getopts is like a receptionist who reads the little switches you add to a command, such as a flag and its value, and hands them neatly to your script.
Syntax
bash
while getopts "optstring" option; do
  case $option in
    a) commands ;;
    b) value=$OPTARG ;;
    *) usage ;;
  esac
done

Script Arguments with getopts

getopts parses short command-line flags like -f file or -v, handling common conventions like combined flags and required option arguments.

It's the standard, POSIX-compatible way to build a script with proper flag parsing instead of manually checking $1, $2. Each recognized option is handled in a case inside the while getopts loop.

Note: A colon after an option letter in the options string, like "f:", means that option requires an argument.

Example: Script Arguments with getopts

bash
#!/bin/bash
verbose=false
filename=""

while getopts "vf:" opt; do
    case $opt in
        v) verbose=true ;;
        f) filename=$OPTARG ;;
        *) echo "Unknown option" ;;
    esac
done

echo "Verbose: $verbose"
echo "Filename: $filename"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting the colon after an option letter that needs a value.
  2. Forgetting to use shift $((OPTIND-1)) after parsing options.
  3. Expecting getopts to handle long options like --help.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.