user2223066
user2223066

Reputation: 43

looping over arguments in bash

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.)

Upvotes: 4

Views: 7209

Answers (3)

Gordon Davisson
Gordon Davisson

Reputation: 125708

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.

Upvotes: 7

glenn jackman
glenn jackman

Reputation: 246754

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  

Upvotes: 7

jedwards
jedwards

Reputation: 30200

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

Upvotes: 7

Related Questions