LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   wrapper script using getopts to pass all arguments except one (https://www.linuxquestions.org/questions/linux-newbie-8/wrapper-script-using-getopts-to-pass-all-arguments-except-one-4175501726/)

threezerous 04-14-2014 05:50 PM

wrapper script using getopts to pass all arguments except one
 
I have a wrapper script which need to execute the base script, when there is no lock, by accepting all arguments except the -F option. I got so far as below, but not sure how I can ignore the -F switch.
Code:

FILENAME=/somedir/test.sh

if [ ! -x $FILENAME ]; then
    echo "File '$FILENAME' is not present or is not executable"
    exit 1
fi

# check if lockfile exists
LOCKFILE=/var/run/lockfile.lck
if [ -f $LOCKFILE ];then
  while getopts ":F" opt; do
      case $opt in
        F)
            echo "Lock file present, running with force enabled"
            exec ${FILENAME} "$@"
            ;;
        \?)
            echo "script locked."
            exit 2
        ;;
      esac
  done
else
  exec ${FILENAME} "$@"
fi

Whenever it tries to run ${FILENAME} "@" it should ignore -F switch but accept any remaining switches (it may not have any other switches either).

Any suggestions if this is feasible and how we can go about it? I was thinking of adding an argument count and then go through each argument and skip -F. But I am not sure that is the best/efficient way. Hoping there is a better way. Thanks much

jlinkels 04-14-2014 06:08 PM

I would take the complete option string which is passed to the wrapper script. Then replace "-F" by a space. Then pass the result to your original script.

In case that you need to know whether "-F" was included in the original call you can search for that occurrence in the option string. Since you don't have to inspect each option and act upon it, this might be feasible.

Unless of course in the call can be a string which also holds "-F" like "MY-FILE". Then you could search for <space>-F<space>.

If that all is not feasible you can't avoid actually parsing all options. When you don't parse you don't know what is an option and what not.

Check for Bash string functions if you can use the search/replace option.

If not and you have to parse, I found this script very helpful: http://code.google.com/p/shflags/

jlinkels


All times are GMT -5. The time now is 12:36 AM.