Using getopts in a custom function in the bourne shell

Is it possible to pass command line arguments to a function from a bourne script to allow getopts to handle them.

The rest of my script is nicely packed in a function, but it starts to look like I have to move the processing of arguments into the main logic.

The following describes how it is written, but it does not 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 define a function so that it can read args scripts? Can this be done in another way? I like the functionality of getopts, but it seems that in this case I will have to sacrifice the beauty of the code to get it.

+4
source share
1 answer

You can provide args for getopts after the variable. The default value is $@ , but also shell functions to represent its arguments. The solution is to pass "$ @" - representing all script command line arguments as separate lines - to processArgs:

  processArgs " $@ "

Add this to your script (and commit the citation on line 11) and try some of the tablet test arguments:

  $ ./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
+6
source

All Articles