4

In bash, I can loop over all arguments, $@. Is there a way to get the index of the current argument? (So that I can refer to the next one or the previous one.)

3 Answers 3

7

Not exactly as you specify, but you can iterate over the arguments a number of different ways.

For example:

while test $# -gt 0
do
    echo $1
    shift
done
Sign up to request clarification or add additional context in comments.

Comments

7

Pretty simple to copy the positional params to an array:

$ set -- a b c d e    # set some positional parameters
$ args=("$@")         # copy them into an array
$ echo ${args[1]}     # as we see, it's zero-based indexing
b

And, iterating:

$ for ((i=0; i<${#args[@]}; i++)); do
    echo "$i  ${args[i]}  ${args[i-1]}  ${args[i+1]}"
  done
0  a  e  b
1  b  a  c
2  c  b  d
3  d  c  e
4  e  d  

Comments

7

You can loop over the argument numbers, and use indirect expansion (${!argnum})to get the arguments from that:

for ((i=1; i<=$#; i++)); do
    next=$((i+1))
    prev=$((i-1))
    echo "Arg #$i='${!i}', prev='${!prev}', next='${!next}'"
done

Note that $0 (the "previous" argument to $1) will be something like "-bash", while the "next" argument after the last will come out blank.

1 Comment

This is really nice thing as one can check parameter and its next parameter in a pair (e.g: --param value).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.