Skip to content

Command-Line Option Parsing in Bash Scripts

Discover examples of command-line option parsing in Bash scripts using getopts and getopt. These examples showcase techniques for efficiently handling user input and options, enabling seamless interaction with your scripts. Whether you're processing simple options or options with arguments, these examples provide valuable insights for enhancing script functionality and usability through effective command-line option parsing.

Example Script
#!/bin/bash

main_function() {
    echo "a"
}

c() {
    echo "Triggered: c"
}

d() {
    echo "Triggered: d"
}

e() {
    echo "Triggered: e"
}

if [[ "$1" == "-e" ]]; then
    main_function
    shift
    if [[ "$1" == "-b" ]]; then
        shift
        case "$1" in
        c)
            c
            ;;
        d)
            d
            ;;
        e)
            e
            ;;
        *)
            echo "Internal error: -b must be used with one of c, d, or e"
            ;;
        esac
    elif [[ -n "$1" ]]; then
        echo "Invalid usage: -b must be used with -e"
    fi
    fi
Example Script 2
#!/bin/bash

# Process command line options using getopt
options=$(getopt -o abc: -- "$@")

if [[ $? -ne 0 ]]; then
    echo "Invalid option"
    exit 1
fi

eval set -- "$options"

while true; do
    case "$1" in
        -a)
            echo "Option a is selected."
            shift
            ;;
        -b)
            echo "Option b is selected."
            shift
            ;;
        -c)
            value="$2"
            echo "Option c is selected with value: $value"
            shift 2
            ;;
        --)
            shift
            break
            ;;
        *)
            echo "Invalid option"
            exit 1
            ;;
    esac
done