Skip to content

Linux getopts Guide

Mattscreative edited this page Nov 20, 2025 · 2 revisions

⚙️ Linux getopts Guide

Complete beginner-friendly guide to getopts on Linux, covering Arch Linux, CachyOS, and other distributions including built-in option parsing, shell option handling, and script argument parsing.


📋 Table of Contents

  1. getopts Basics
  2. Option Parsing
  3. Options with Arguments
  4. Error Handling
  5. Troubleshooting

⚙️ getopts Basics

Parse Options

Basic usage:

#!/bin/bash
while getopts "hv" opt; do
    case $opt in
        h)
            echo "Help"
            ;;
        v)
            VERBOSE=1
            ;;
    esac
done

Option String

Option format:

# Option string: "hv"
# h = help flag
# v = verbose flag

🔧 Option Parsing

Simple Options

Basic flags:

#!/bin/bash
while getopts "hv" opt; do
    case $opt in
        h) echo "Help message" ;;
        v) VERBOSE=1 ;;
        \?) echo "Invalid option" ;;
    esac
done

Multiple Options

Multiple flags:

# Multiple options
while getopts "abc" opt; do
    case $opt in
        a) OPTION_A=1 ;;
        b) OPTION_B=1 ;;
        c) OPTION_C=1 ;;
    esac
done

📝 Options with Arguments

Required Arguments

Option with value:

# Option with argument
while getopts "f:" opt; do
    case $opt in
        f)
            FILE=$OPTARG
            ;;
    esac
done

# Usage: script.sh -f filename.txt

Optional Arguments

Optional value:

# Optional argument (GNU extension)
while getopts "f::" opt; do
    case $opt in
        f)
            FILE=${OPTARG:-default.txt}
            ;;
    esac
done

⚠️ Error Handling

Invalid Options

Handle errors:

#!/bin/bash
while getopts "hv" opt; do
    case $opt in
        h) echo "Help" ;;
        v) VERBOSE=1 ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            exit 1
            ;;
        :)
            echo "Option -$OPTARG requires argument" >&2
            exit 1
            ;;
    esac
done

🔧 Troubleshooting

getopts Not Found

Check installation:

# getopts is built-in shell command
# Always available in bash

# Check bash
which bash

📝 Summary

This guide covered getopts usage, built-in option parsing, and script argument handling for Arch Linux, CachyOS, and other distributions.


🔗 Next Steps


This guide covers Arch Linux, CachyOS, and other Linux distributions. For distribution-specific details, refer to your distribution's documentation.

Clone this wiki locally