Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing shell script arguments by index

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

like image 402
guitarflow Avatar asked Aug 29 '26 05:08

guitarflow


1 Answers

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
like image 160
chepner Avatar answered Aug 31 '26 23:08

chepner