0

I'm writing my first bash script and I'm trying to parse arguments. I have a

for arg in "$@"

loop set up, but I want some arguments to be read together, for instance if the user passes -a info it would find out what $number -a is and also read $number + 1. Is this something I can do?

I could make the loop keep $count ++ each iteration to tell what arg I'm on, and since my script is set to bomb out if it finds something invalid, I set an if statement to continue if a $skip var is above 0, I just need to figure out how to read $arg +1.

I haven't tried much. I'm still new (my first script) at this and I don't know too many commands. Google got me this far, but I hit a wall.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Maybe it's better to take a step back and instead ask [How do I parse command line arguments in Bash?](https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash) – that other guy May 11 '19 at 00:19

1 Answers1

1

Instead of the for arg in "$@" syntax, you can write:

for (( i = 1 ; i <= ${#} ; ++i )) ; do
  arg="${@:i:1}"           # current argument
  next_arg="${@:i+1:1}"    # next argument
  ...
done

The for (( expr1 ; expr2 ; expr3 )) syntax is described in the Bash Reference Manual, § 3.2.4.1 Looping Constructs; the ${@:expr:expr} syntax is described in § 3.5.3 Shell Parameter Expansion. Both rely on shell arithmetic, which is described in § 6.5 Shell Arithmetic.

ruakh
  • 175,680
  • 26
  • 273
  • 307