4

Possible Duplicate:
How do I reverse a for loop?

Is there an easy way to invert a for in loop? For a script I want to process files in their reverse order.

So instead of:

for file in *.jpg;
  do echo $file;
done

with the result

001.jpg
002.jpg
003.jpg
...
150.jpg

I want the result

150.jpg
149.jpg
148.jpg
...
001.jpg
3
  • Ansgar Esztermann's solution will not work on the 'so called' exact duplicate, but on this example here, with numbers in filenames, which makes it a different thing. I vote to reopen. Feb 7, 2012 at 1:44
  • @userunknown That's why I didn't merge them, but the duplicate is a more general case. Why would you want a more specific solution? It helps fewer people Feb 7, 2012 at 2:20
  • The solutions are more easy. Shorter to type, easier to remember. I have an even shorter one and would gain magnitudes of reputation, if I could publish it! :) Feb 7, 2012 at 3:52

2 Answers 2

9

You can use

array=(*.jpg)
for ((i = ${#array[@]} - 1;i >= 0;i--)); do
    echo ${array[i]}
done
2

In the given example, you could use

for num in `seq -w 150 -1 1`
  do echo $num.jpg
done

This is, of course, not totally equivalent, as it does not really invert the globbing, but instead generates the sequence externally.

0

Not the answer you're looking for? Browse other questions tagged .