Skip to content

See dot files at top of ls output in Linux

In Terminal on macOS, the ls (list directory contents) command sorts the output of its "all files" listing so that hidden files (those that begin with a dot) appear at the top of the list, like this:

$ ls -Alh
total 47640
-rw-r--r--@   1 robg  staff    28K Oct 26 15:00 .DS_Store
drwxrwxrwx@   5 robg  staff   160B Oct 23  2016 .TemporaryItems
... [trimmed for display]
drwxr-xr-x    8 robg  staff   256B Sep 19 08:31 .wine
drwx------   13 robg  staff   416B Apr 13  2019 Applications
drwx------+  20 robg  staff   640B Oct 26 12:36 Desktop
... [trimmed for display]

On the server that hosts my personal sites (as well as Many Tricks), however, ls doesn't sort the invisible files to the top:

$ ls -Alh
... [trimmed for display]
drwxr-x---.  4 rgriff mail     82 Oct 21 14:59 etc
drwxr-x---. 13 rgriff nobody  160 Oct 26 15:06 .htpasswds
-rw-------.  1 rgriff rgriff  503 Oct 20 21:02 .lastlogin
drwxr-x--x. 11 rgriff rgriff 4.0K Oct 21 17:48 mail
-rw-------.  1 rgriff rgriff    0 Oct 21 14:42 .mysql_history
... [trimmed for display]

I dug around for a solution, but didn't find one. So I came up with a really hacky alias, but it worked:

alias ls="/usr/bin/ls -la | egrep --color=never '[0-9]\ \.';ls -l | tail -n+2"

But really, don't use that. A buddy told me that the solution was a simple matter of changing a locale setting—and he was right. To make linux directory listings sort the dot files to the top, add this to your .bashrc or whatever config file you use:

export LC_COLLATE=C

With that locale value set, the ls output matches what I'm used to from macOS. I don't know much about locale at all, but this page explains it in detail, including this bit about the "C" locale:

The C locale, also known as the POSIX locale, is the POSIX system default locale for all POSIX-compliant systems.

I'm sure I could start there and dive into a deep hole learning about locales and default sort orders, but really, I don't care. I'm just happy that ls is once again sorting the way I prefer.