2010-11-15 6 views
29

Ich möchte sowohl kurze als auch lange Optionen in bash Skripte unterstützen, so kann man:Wie unterstützt man gleichzeitig kurze und lange Optionen in bash?

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

ist es möglich?

+1

See [BashFAQ/035] (http://mywiki.wooledge.org/BashFAQ/035). –

+0

Obwohl das nominierte Duplikat speziell nach "getopts" fragt, gibt es mehrere Antworten, die verschiedene Ansätze nahelegen. Ich stimme dem Schluss zu. – tripleee

Antwort

37

getopt unterstützt lange Optionen.

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

Hier ist ein Beispiel Ihre Argumente mit:

#!/bin/bash 

OPTS=`getopt -o axby -l long-key: -- "[email protected]"` 
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 

Ausgabe von $ 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 
+9

Einige Versionen von 'getopt' haben Probleme mit einigen Zeichen in Argumenten und Nicht-Option-Parametern. Wenn 'getopt --test; echo $? 'gibt" 4 "aus, du bist OK. Wenn es "0" ausgibt, haben Sie eine Version mit diesem Problem. Siehe ['man getopt'] (http://linux.die.net/man/1/getopt) für weitere Informationen. –

+0

Und auch POSIXLY_CORRECT-Umgebung ist nützlich. –

+0

Xiè Jìléi: Warum? Wie stellst du das fest? – Christoph

Verwandte Themen