29

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?

Lenik
  • 13,946
  • 17
  • 75
  • 103

1 Answers1

39

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
strager
  • 88,763
  • 26
  • 134
  • 176
Brian Clements
  • 3,787
  • 1
  • 25
  • 26
  • 9
    Some versions of `getopt` have problems with some characters in arguments and and non-option parameters. If `getopt --test; echo $?` outputs "4", you're OK. If it outputs "0" you have a version with this problem. See [`man getopt`](http://linux.die.net/man/1/getopt) for more information. – Dennis Williamson Nov 15 '10 at 05:05
  • And also POSIXLY_CORRECT environment is useful. – Lenik Nov 16 '10 at 06:17
  • Xiè Jìléi: Why? How do you set that? – Christoph Feb 27 '14 at 13:12
  • 1
    By the way, the link no longer works. Here is a replacement on Archive.Org [https://web.archive.org/web/20090130140546/http://linux.about.com/library/cmd/blcmdl1_getopt.htm](https://web.archive.org/web/20090130140546/http://linux.about.com/library/cmd/blcmdl1_getopt.htm) – Adrian Nov 17 '16 at 21:53