Ordering items

There are lots of small little quirks to the *nix shells; this is just one of them.

If you want to list the files in a directory, then ls will list them all for you, in alphabetical order.

If you want to list them by size, you can use ls -S; by timestamp: ls -t, and so on.

But ls is a particular utility. What happens when we do this:


for myfile in *
do
  echo "My file is called $myfile"
done

We get an alphabetically sorted list (see man ascii for the actual detail; they’re sorted by ASCII value, so numbers first, then uppercase letters, then lowercase letters).

This can be a pain, but it can also be quite useful. If you’ve got a bunch of files:

1.install.txt
2.setup.txt
3.use.txt
4.uninstall.txt

Then you can play with them in order, just by using the asterisk:

for i in *
do
  echo "File $i" >> all.txt
  cat $i >> all.txt
done

And it will sort them into order for you (“1” comes before “2” in ASCII, and so on…)

Or you could just do this:

more * > all.txt

Because more will prefix each file with its name in a header, if there is more than one file to process.

Leave a comment