0

I have a script myscript that should do the following:

  1. Run on its own: myscript
  2. Run with an argument: myscript myarg
  3. Run with options: myscript -a 1 -b 2 -c 3 ...
  4. Run with an argument and options: myscript myarg -a 1 -b 2 -c 3 ...

I cannot get 4. to work, it seems, that using an argument in front of the options (which I take from getopts), interferes with the way how getopts handles everything.

The code I'm using is basically like this:

while getopts "a:b:c:" opt; do
   case ${opt} in
      a)
         var_a=$OPTARG
         ;;
      ... more options here
   esac
done

if [ ! -z "$1" ] && [[ ! "$1" =~ ^- ]]; then
      ... do stuff with first argument - if it's there and it's not just an option
fi

If there is a simple solution to this problem, I'd be very thankful!

Cyrus
  • 84,225
  • 14
  • 89
  • 153
snurden
  • 173
  • 5
  • 2
    Did you think to use shift to get rid of the first argument? – linuxfan says Reinstate Monica Jan 12 '17 at 11:26
  • This is indeed super simple, thanks! I guess the question can be closed, do you want to post it as an answer? Or should I write an answer? One potential downside of the solution: the `if [condition] then ... shift ... fi` has to be used before `getopts` is called, which might be an issue (but not in my case). – snurden Jan 12 '17 at 11:38
  • Unless you want to support `myscript -a 1 myarg -b 2 -c 3`, there will be no issue with running `if [[ $1 == myarg ]]; then shift; ...; fi` before your `getopts` loop. – chepner Jan 12 '17 at 12:54

1 Answers1

1

You can use shift in the last if of the script (the general idea is already there, as you write "do stuff with first argument - if it's there and it's not just an option").