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

marked as duplicate by Michael Mrozek Feb 6 '12 at 14:40

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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. – user unknown Feb 7 '12 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 – Michael Mrozek Feb 7 '12 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! :) – user unknown Feb 7 '12 at 3:52
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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.