Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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;

with the result


I want the result

share|improve this question

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
up vote 9 down vote accepted

You can use

for ((i = ${#array[@]} - 1;i >= 0;i--)); do
    echo ${array[i]}
share|improve this answer

In the given example, you could use

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

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

share|improve this answer

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