dimanche 1 février 2015

Calling bash getopts from a function fails the 2nd time


I'm trying to parse arguments passed to a bash function using getopts inside that function. It works when the function is called for the first time but fails on all subsequent calls.


Here is a simple test case:



#!/bin/bash

function getopt_test {
PARAMS=""
while getopts "a:" opt; do
case $opt in
a)
PARAMS="${PARAMS} $OPTARG"
;;
esac
done
echo "PARAMS => $PARAMS"
}

getopt_test -a call_1
getopt_test -a call_2


The output of the script is this:



~$ ./tst.sh
PARAMS => call_1
PARAMS => <--- missing 'call_2'
~$


I guess getopts should somehow be reset before calling it for the second time but I can't really figure out how. Any ideas?



Aucun commentaire:

Enregistrer un commentaire