简体   繁体   中英

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

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

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.

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  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM