Accessing shell script arguments by index

2020-02-06 05:03发布

I'm sure this is a no-brainer when you're into shell programming. Unfortunately I'm not and I'm having a pretty hard time ...

I need to verify arguments passed to a shell script. I also want to store all parameters passed in an array as I need further separation later.

I have an argument "-o" which must be followed by either 0 or 1. Thus, I want to check if the following argument is valid. Here's what I tried:

# Loop over all arguments
for i in "$@"
do
    # Check if there is a "-" as first character,
    # if so: it's a parameter
    str="$i"
    minus=${str:0:1}

    # Special case: -o is followed by 0 or 1
    # this parameter needs to be added, too
    if [ "$str" == "-o" ]
    then
        newIdx=`echo $((i+1))`   # <-- problem here: how can I access the script param by a generated index?
        par="$($newIdx)"

        if [[ "$par" != "0" || "$par" != "1" ]]
        then
            echo "script error: The -o parameter needs to be followed by 0 or 1"
            exit -1
        fi
        paramIndex=$((paramIndex+1))

    elif [ "$minus" == "-" ]
    then
        myArray[$paramIndex]="$i"
        paramIndex=$((paramIndex+1))
    fi
done

I tried various things but it didn't work ... Would be grateful if someone could shed light on this!

Thanks

2条回答
【Aperson】
2楼-- · 2020-02-06 05:34

In bash, you can use indirect parameter expansion to access an arbitrary positional parameter.

$ set a b c
$ paramIndex=2
$ echo $2
b
$ echo ${!paramIndex}
b
查看更多
叛逆
3楼-- · 2020-02-06 05:40

There is no method to access next argument in for.

  1. How about to rewriting your script to use getopt?

  2. If you don't like getopt, try to rewrite your script using shift:


while [ -n "$1" ]
do
  str="$1"
  minus=${str:0:1}
  if [ "$str" == "-o" ]
  then
    shift
    par="$1"
#  ...
  elif [ "$minus" == "-" ]
  then
    # append element into array
    myArray[${#myArray[@]}]="$str"
  fi

  shift
done
查看更多
登录 后发表回答