loop with more than one item at a time loop with more than one item at a time unix unix

loop with more than one item at a time


Assuming you don't have too many items (although the shell should be able tohandle quite a few positional arguments.

# Save the original positional arguments, if you need themoriginal_pp=( "$@" )set -- *while (( $# > 0 )); do    i=$1 j=$2 k=$3     # Optional; you can use $1, $2, $3 directly    ...    shift 3 || shift $#   # In case there are fewer than 3 arguments leftdone# Restore positional arguments, if necessary/desiredset -- "${original_pp[@]}"

For POSIX compatibility, use [ "$#" -gt 0 ] instead of the ((...)) expression. There's no easy way to save and restore all the positional parameters in a POSIX-compatible way. (Unless there is a character you can use to concatenate them unambiguously into a single string.)

Here is the subshell jm666 mentions:

(    set -- *    while [ "$#" -gt 0 ]; do        i=$1 j=$2 k=$3        ...        shift 3 || shift $#    done)

Any changes to parameters you set inside the subshell will be lost once the subshell exits, but the above code is otherwise POSIX-compatible.


If filenames does not contain spaces:

find . -maxdepth 1 | xargs -L 3 | while read i j k; do  echo item i: $i  echo item j: $j  echo item k: $kdone

Edit:

I removed -print0 and -0.


To get to get n items a time from the list I think you want to get n items from an array.

Use it like this:

n=3arr=(a b c d e)echo "${arr[@]:0:$n}"a b c