Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a folder with about 40 SQL scripts with varying names, All using the pattern number description.sql. The file number consist of 2 digits and goes from 01 to 40, not all numbers in this range included.

I would like to iterate over this folder with files and run them via mysql cmd in a DESC filename order.

How can I run them all via mysql cmd in order of descending file number? Thanks.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

If you wanted to run the scripts in ascending lexicographic order, you could do

for x in *.sql; do
  mysql <"$x"
done

Listing the files in descending order can be done easily in zsh Install zsh, thanks to the O glob qualifier, but there is no corresponding feature in bash. At a zsh prompt:

for x in *.sql(On); do
  mysql <"$x"
done

By the way, if your numbers didn't have a leading 0, you could use (nOn) here, to sort 9 foo.sql before 10 bar.sql.

Using only programs that are in a default installation (plus mysql), you can list the files, sort them as desired with sort (or directly reverse the order with tac), and iterate over the result.

for x in *.sql; do echo "$x"; done |
tac |
while IFS= read -r script; do mysql <"$script"; done
share|improve this answer
    
I have used the zsh solution. Works like a charm :) Thank you for the full answer. –  TR7 Jun 4 '12 at 7:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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