4

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.

AgentConundrum
  • 20,288
  • 6
  • 64
  • 99

1 Answers1

6

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
Nietzche-jou
  • 14,415
  • 4
  • 34
  • 45
  • 5
    I also recommend using `local OPTIND` inside the function to prevent bugs when optargs is called more than once due to the function being called multiple times. – Dennis Williamson Jan 09 '12 at 16:28
  • I found when defining a function and calling it from an interactive shell, the 'local OPTIND' was required for proper behavior. – Von Apr 28 '12 at 13:06