How to support both short and long options at the same time in bash?

26,459

getopt supports long options.

http://man7.org/linux/man-pages/man1/getopt.1.html

Here is an example using your arguments:

#!/bin/bash

OPTS=`getopt -o axby -l long-key: -- "$@"`
if [ $? != 0 ]
then
    exit 1
fi

eval set -- "$OPTS"

while true ; do
    case "$1" in
        -a) echo "Got a"; shift;;
        -b) echo "Got b"; shift;;
        -x) echo "Got x"; shift;;
        -y) echo "Got y"; shift;;
        --long-key) echo "Got long-key, arg: $2"; shift 2;;
        --) shift; break;;
    esac
done
echo "Args:"
for arg
do
    echo $arg
done

Output of $ foo -ax --long-key val -b -y SOME FILE NAMES:

Got a
Got x
Got long-key, arg: val
Got b
Got y
Args:
SOME
FILE
NAMES
Share:
26,459
Lenik
Author by

Lenik

+--[ RSA 1024]----+ | | | | | . . o | | . o o o o | | S . o + .| | . . + + o | | . . . . . o + | | = o . o . | | =.. ooE| +-----------------+ 1024 aa:0c:4f:fb:15:5c:7e:4c:e7:f1:ca:61:8a:fd:0f:fe X.J. Lenik (RSA)

Updated on December 04, 2020

Comments

  • Lenik
    Lenik over 3 years

    I want to support both short and long options in bash scripts, so one can:

    $ foo -ax --long-key val -b -y SOME FILE NAMES
    

    is it possible?