Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash for loop get previous and next item

Tags:

bash

loops

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?

like image 567
Guillaume Avatar asked Dec 01 '12 11:12

Guillaume


People also ask

What does %% mean in bash?

So as far as I can tell, %% doesn't have any special meaning in a bash function name. It would be just like using XX instead. This is despite the definition of a name in the manpage: name A word consisting only of alphanumeric characters and under- scores, and beginning with an alphabetic character or an under- score.

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

Does bash have a Continue statement?

The Bash continue statement resumes the following iteration in a loop or looping statement. The continue statement only has meaning when applied to loops. The integer value indicates the depth for the continue statement. By default, the integer is 1 and writing the number is not mandatory.

Is there a for loop in bash?

A bash for loop is a bash programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a bash script. For example, you can run UNIX command or task 5 times or read and process list of files using a for loop.


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, the index -1 will print the last element and in the last iteration, the index max+1 will not print anything.

like image 165
Vivek Avatar answered Oct 18 '22 15:10

Vivek


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
like image 1
Pavel Strakhov Avatar answered Oct 18 '22 15:10

Pavel Strakhov