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
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
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
Bằng Rikimaru
This is really nice thing as one can check parameter and its next parameter in a pair (e.g: --param value).