1

I'd like to have named parameters for my functions.

I seem to only be able to use GETOPTS for the main function called from the command line.

If I have multiple functions within one file is there any way I can get the same sort of functionality (named parameters) when calling other functions ?

e.g. the following does not seem to work:

$ cat getops_example.sh 
function usage {
  echo 'here'
}

function my_test {
while getopts ":s:p:" o; do
    case "${o}" in
        s)
            s=${OPTARG}
            ((s == 45 || s == 90)) || usage
            ;;
        p)
            p=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done
}
my_test 11 20
echo "s was $s"
echo "p was $p"
$

$ ./getops_example.sh -s 10 -p 20
s was 
p was 
  • You need to make sure you do OPTIND=1 preceding every set of parameters you want to work with. So if you do getopts... for your script args and then attempt to do getopts within a function, reset $OPTIND before each getopts processing loop. – mikeserv Mar 10 '15 at 3:13
2

Your program does not work because you pass parameters to your program but inside the program you call your function my_test without the option flags -s and -p resp. Depending what you actually want, use either

my_test -s 11 -p 20

or pass the arguments from outside and call your function as

my_test "$@"
  • Thanks. What if the values themselves are not determined until the actual call. This is what I am looking for (I should have been clearer in my example, was trying to give a simple example). – Michael Durrant Mar 9 '15 at 21:31
  • Michael, for variable values passed from outside use the second form of my answer. – Janis Mar 9 '15 at 21:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.