Guillaume
Guillaume

Reputation: 9061

Bash for loop get previous and next item

I would like to do a loop and inside the loop get the previous and the next item.

Currently, I am using the following loop:

for file in $dir;do
    [...do some things...]
done

Can I do things like in C, for example, file[i-1]/file[i+1] to get the previous and the next item? Is there any simple method to do this?

Upvotes: 8

Views: 10098

Answers (2)

Pavel Strakhov
Pavel Strakhov

Reputation: 40502

Try this:

previous=
current=
for file in *; do
  previous=$current
  current=$next
  next=$file
  echo $previous \| $current \| $next 
  #process item
done
previous=$current
current=$next
next=
echo $previous \| $current \| $next 
#process last item

Upvotes: 2

Vivek
Vivek

Reputation: 2020

declare -a files=(*)
for (( i = 0; i < ${#files[*]}; ++ i ))
do
  echo ${files[$i-1]} ${files[$i]} ${files[$i+1]}
done

In the first iteration, the index -1 will print the last element and in the last iteration, the index max+1 will not print anything.

Upvotes: 7

Related Questions