Bash script: iterating from the last item

NetRock6
NetRock6 used Ask the Experts™
on
Hi..
I have a file similar to the below example:

/../../PVD
/../../PVD1
/../../PVD2
/../..PVD3

In a bash script How can I 'for' loop from the last item to process an action.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
David FavorFractional CTO
Distinguished Expert 2018

Commented:
Usually, you'll read values into an array + then walk the array in reverse.

https://stackoverflow.com/questions/13360091/how-to-reverse-array-in-bash-onliner-for-loop provides a great example of walking an array in reverse.
Software Engineer
Distinguished Expert 2018
Commented:
How about using the tac command (it does the opposite of cat), it copies files from end to start
$ 
$ for i in ( 1 2 3 4 ) ; do echo $i ; done >t.t1
$ cat t.t1
1
2
3
4
$ tac t.t1
4
3
2
1
$ for i in (5 6 7 8) ; do echo $i ; done | tac 

Open in new window


so:

[code]#!/bin/bash
for i in $( tac The.File.You.Want.End.To.Start )
do
    do_something_useful
done

Open in new window


Or reversing some output:

produce_some_output | tac | do_something_with_end_to_start

Open in new window

Author

Commented:
Great idea noci.... THANK You!

Thank you David for the useful link and your quick prompts.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial