For cycle, process order

Hello,
I am running a script under ubuntu 16.04
I have no problem with the script. My question is general algorithm of for file command.
I just need to know how for file in *.txt process works.

Let's say, I wish to run the script by sorting filename:

for file in *.txt
do
"do something in alphabetical order"
done

or

for file in *.txt
do
"do something according to filesize in ascending direction"
done

or another way:

for file in *.txt
do
"do something in by recently updated file"
done

or

for file in *.txt
do
"do something by total string length of each filename in descending order"
done

In summarize: If we do not indicate any criteria, what's the default working method of for cycle ?
Thank you
Boris

It's not the for cycle's feature but the way the shell expands the "glob"s using "pattern matching". man bash is your friend:

For any other arrangement of the value list, additional measures must be taken.

1 Like

Why not check it by creating some files and doing for loop with a simple echo ?
Default order of things should be apparent from the output produced.

As for other requirements, it will have to be coded for each case specifically using if , case or both, piped to sort command or whatever.
Some like length of filename shell builtin can be used e.g. ${#i}

For sorting requirement per modified time a simple example for mtime change
Last modified file will be last printed on the screen.
Code assumes there are not comma , in filenames.

for i in *.txt; do printf "%s," $i ; stat -c %Y $i; done | sort -t, -k2

Hope that helps
Regards
Peasant.

2 Likes