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

Script Arguments with getopts

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"

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.