Skip to content

Linux getopt Guide

Mattscreative edited this page Dec 5, 2025 · 2 revisions

Linux getopt Guide

Complete beginner-friendly guide to getopt on Linux, covering Arch Linux, CachyOS, and other distributions including command-line option parsing, argument parsing, and script option handling.


Table of Contents

  1. getopt Basics
  2. Option Parsing
  3. Long Options
  4. Script Usage
  5. Troubleshooting

getopt Basics

Parse Options

Basic usage:

# Parse options
getopt -o "abc:" -- "$@"

# -o = options (a, b, c with argument)

Short Options

Short flags:

# Short options
getopt -o "hv" -- "$@"

# -h = help
# -v = verbose

Option Parsing

With Arguments

Options with values:

# Option with argument
getopt -o "f:" -- "$@"

# -f = file (requires argument)

Multiple Options

Multiple flags:

# Multiple options
getopt -o "abc:d" -- "$@"

# a, b, c (with arg), d

Long Options

Long Format

Long options:

# Long options
getopt -l "help,verbose,file:" -- "$@"

# --help, --verbose, --file=value

Combined

Short and long:

# Both formats
getopt -o "hv" -l "help,verbose" -- "$@"

# Supports both -h and --help

Script Usage

In Scripts

Script example:

#!/bin/bash
OPTS=$(getopt -o "hv" -l "help,verbose" -- "$@")
eval set -- "$OPTS"

while true; do
    case "$1" in
        -h|--help)
            echo "Help message"
            shift
            ;;
        -v|--verbose)
            VERBOSE=1
            shift
            ;;
        --)
            shift
            break
            ;;
    esac
done

Troubleshooting

getopt Not Found

Check installation:

# getopt is part of util-linux
# Usually pre-installed

# Check getopt
which getopt

Summary

This guide covered getopt usage, option parsing, and command-line 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