Bash for loop get previous and next item

I would like to make a loop and get the previous and next elements inside the loop. Currently, I used the following bouquet:

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

Is it possible to do something like C, for example, the file [i-1] / file [i + 1] to get the previous and next elements? Is there an easy way to do this.

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

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

+8
source

Try the following:

 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 
0
source

All Articles