Using getopts within user-defined-function in bourne shell

getoptsshshell

Is it possible to pass command line arguments into a function from within a bourne script, in order to allow getopts to process them.

The rest of my script is nicely packed into functions, but it's starting to look like I'll have to move the argument processing into the main logic.

The following is how it's written now, but it doesn't work:

processArgs()
{
  while getopts j:f: arg
  do
  echo "${arg} -- ${OPTARG}"
     case "${arg}" in
       j)  if [ -z "${filename}" ]; then
           job_number=$OPTARG
           else
              echo "Filename ${filename} already set."
              echo "Job number ${OPTARG} will be ignored.
           fi;;
       f)  if [ -z "${job_number}" ]; then
              filename=$OPTARG
           else
              echo "Job number ${job_number} already set."
              echo "Filename ${OPTARG} will be ignored."
           fi;;
     esac
  done
}

doStuff1
processArgs
doStuff2

Is it possible to maybe define the function in a way that it can read the scripts args? Can this be done some other way? I like the functionality of getopts, but it looks like in this case I'm going to have to sacrifice the beauty of the code to get it.

Best Answer

You can provide args to getopts after the variable. The default is $@, but that's also what shell functions use to represent their arguments. Solution is to pass "$@" — representing all the script's command-line arguments as individual strings — to processArgs:

processArgs "$@"

Adding that to your script (and fixing the quoting in line 11), and trying out some gibberish test args:

$ ./try -j asdf -f fooo -fasdfasdf -j424pyagnasd
j -- asdf
f -- fooo
Job number asdf already set.
Filename fooo will be ignored.
f -- asdfasdf
Job number asdf already set.
Filename asdfasdf will be ignored.
j -- 424pyagnasd