0

I want to be able to search through passed arguments before my code executes, and allocate the different variable names depending on the type of input it is (e.g. file).

My program works if I type:

./program input.txt -a

But when I type:

./program -a input.txt

My program fails.

It fails because my first line of code is:

FILE=$1

And -a is not a file, so how can I 'skip' this, and move onto the next passed argument and check if it's a file?

Any help is appreciated, thank you in advance. :)

Michael Jaros
  • 4,586
  • 1
  • 22
  • 39
xiora
  • 3
  • 1
  • Always use standard tools for argument processing, it saves you and others a lot of time. To learn more, have a look at the question @Mat just posted, or at my related [answer](http://stackoverflow.com/a/29731392/4024473) here. – Michael Jaros Apr 21 '15 at 08:26

1 Answers1

0

Well, you can easily manage it with this:

if [[ "$1" =~ ^-a$ ]]; then
    flag_a=1 # variable flag_a stores a -a was issued on arguments
    shift # $2 is now $1
fi

On the other hand you can use the much more elegant bash's getopts: http://wiki.bash-hackers.org/howto/getopts_tutorial

olopopo
  • 296
  • 1
  • 8