2017-02-03 1 views
2

Ich versuche Argumente an ein Skript zu übergeben, das ich geschrieben habe, aber ich kann es nicht richtig machen.Bash-Skriptargumente

Was ich will, ist ein obligatorisches Argument ohne Flag und zwei optionale Argumente mit Fahnen, so kann es wie folgt aufgerufen werden:

./myscript mandatory_arg -b opt_arg -a opt_arg 

oder

./myscript mandatory_arg -a opt_arg 
./myscript mandatory_arg -b opt_arg 

Ich sah in getopts und hab das:

while getopts b:a: option 
do 
    case "${option}" 
    in 
     b) MERGE_BRANCH=${OPTARG};; 
     a) ACTION=${OPTARG};; 
    esac 
done 

if "$1" = ""; then 
    exit 
fi 

echo "$1" 
echo "$MERGE_BRANCH" 
echo "$ACTION" 

Aber es funktioniert überhaupt nicht.

Antwort

3

Unter der Annahme, dass Ihr obligatorisches Argumentletzte erscheint, sollten Sie den folgenden Code versuchen: [Kommentare inline]

OPTIND=1 
while getopts "b:a:" option 
do 
    case "${option}" 
    in 
     b) MERGE_BRANCH=${OPTARG};; 
     a) ACTION=${OPTARG};; 
    esac 
done 

# reset positional arguments to include only those that have not 
# been parsed by getopts 

shift $((OPTIND-1)) 
[ "$1" = "--" ] && shift 

# test: there is at least one more argument left 

((1 <= ${#})) || { echo "missing mandatory argument" 2>&1 ; exit 1; }; 

echo "$1" 
echo "$MERGE_BRANCH" 
echo "$ACTION" 

Das Ergebnis:

~$ ./test.sh -b B -a A test 
test 
B 
A 
~$ ./tes.sh -b B -a A 
missing mandatory argument 

Wenn Sie wirklich wollen, das mandato ry Argumenterste erscheinen, dann können Sie das Folgende tun:

MANDATORY="${1}" 
[[ "${MANDATORY}" =~ -.* ]] && { echo "missing or invalid mandatory argument" 2>&1; exit 1; }; 

shift # or, instead of using `shift`, you can set OPTIND=2 in the next line 
OPTIND=1 
while getopts "b:a:" option 
do 
    case "${option}" 
    in 
     b) MERGE_BRANCH=${OPTARG};; 
     a) ACTION=${OPTARG};; 
    esac 
done 

# reset positional arguments to include only those that have not 
# been parsed by getopts 

shift $((OPTIND-1)) 
[ "$1" = "--" ] && shift 

echo "$MANDATORY" 
echo "$MERGE_BRANCH" 
echo "$ACTION" 

Das Ergebnis ist folgendes:

~$ ./test.sh test -b B -a A 
test 
B 
A 
~$ ./tes.sh -b B -a A 
missing or invalid mandatory argument 
+0

Beim Versuch, dies auszuführen es druckt das obligatorische Argument aus und dann " "Für die Optionals, wenn ich ohne das obligatorische ausführen, antwortet es mit" fehlendes obligatorisches Argument " –

+0

Was ist der Grund dafür, das obligatorische Argument nicht zuerst zu empfehlen? und ich denke etwas fehlt von der letzten Bearbeitung –

+0

@ A.Jac es ist nur eine Frage der * Konvention * und * persönlichen Geschmack * –