-1

I'm writing a bash script which will input arguments, the command would look like this:

command -a -b -c file -d -e

I would like to detect a specific argument (-b) with its specific location ($1, $2, $3)

#! /bin/bash
counter=0
while [ counter -lt $# ]
do
    if [ $($counter) == "-b" ]
    then
        found=$counter
    fi
    let counter+=1
done

The problem rises in $($counter). Is there a way to use $counter to call the value of an argument? For instance if counter=2, I would like to call the value of argument $2. $($counter) doesn't work.

Rubens
  • 14,478
  • 11
  • 63
  • 92
Michael Ho Chum
  • 939
  • 8
  • 17

1 Answers1

2

You can accomplish this without getopts (which is still recommended, though) by reworking your loop.

counter=1
for i in "$@"; do
  if [[ $i == -b ]]; then
      break
  fi
  ((counter+=1))
done

Simply iterate over the arguments directly, rather than iterating over the argument positions.


bash also does allow indirect parameter expansion, using the following syntax:

#! /bin/bash
counter=0
while [ counter -lt $# ]
do
    if [ ${!counter} = "-b" ]  # ${!x} uses the value of x as the parameter name
    then
        found=$counter
    fi
    let counter+=1
done
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    Don't use `==` with single-bracket notation, `bash` accepts it but it's not POSIX-conforming and other shells choke on it. +1 for the rest! – Adrian Frühwirth Oct 17 '13 at 13:38
  • Non-POSIX shells will probably choke on `${!counter}` anyway :) But you are correct in general. – chepner Oct 17 '13 at 13:52