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?
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?
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
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. –
Und auch POSIXLY_CORRECT-Umgebung ist nützlich. –
Xiè Jìléi: Warum? Wie stellst du das fest? – Christoph
See [BashFAQ/035] (http://mywiki.wooledge.org/BashFAQ/035). –
Obwohl das nominierte Duplikat speziell nach "getopts" fragt, gibt es mehrere Antworten, die verschiedene Ansätze nahelegen. Ich stimme dem Schluss zu. – tripleee