Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping over arguments in bash

Tags:

bash

shell

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

like image 469
user2223066 Avatar asked Dec 03 '22 23:12

user2223066


1 Answers

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.

like image 129
Gordon Davisson Avatar answered Jan 03 '23 01:01

Gordon Davisson