snurden
snurden

Reputation: 193

Use optional argument before options on command line in a bash script

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!

Upvotes: 0

Views: 660

Answers (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").

Upvotes: 1

Related Questions