MacOS – Sort folders first, then files [El Capitan]

findermacossortterminal

I am aware there are many posts about this problem, but many are just workarounds for Finder. However I use console more often then Finder because of programming.

I am also aware of something like this (after getting coreutils):

alias ll='gls -la -h --group-directories-first'

But thats just another 'plugin' or external utility, which does the job well but doesn't answer my question.

I also found out that Dropbox web also sorts your files according to the User Agent. If it is changed from the Develop menu in Safari to IE or Firefox/Chrome (Widows) then it sorts folders first.

I get that OS X and Windows must be rebels so they use different sorting but frankly it's a mess when you got plenty files and they all get mixed up.

Does OS X have a system wide setting for this so when I type ls -la output is sorted folders first then files and both are alphabetically ascending (a to z)? Or is the sorting mechanism related to the implementation of program/application which is displaying files?

Best Answer

I think the simple answer is no, if the question is whether the native ls command can be configured to list directories before it lists non-directories. One of the comments suggests a shell pipeline, but rather than going to that trouble it might be easier to write a script.

The following python code is by no means intended to be a complete substitute for the ls command, but complicating it to handle more of what ls provides feels doable (python's argparse module would help with that).

#!/usr/bin/python                                                                                                                                                                    

import os
import sys

for top in sys.argv[1:]:
    for (name, dirs, files) in os.walk(top):
        print("{}:".format(name))
        for dir in dirs:
            print("{}/".format(dir))
        for file in files:
            print(file)

What makes the separation of directories from non-directories easy in this example is that python's os.walk does that for me, in its return value. The use of os.walk implicitly imposes the equivalent of ls -R, but that should be easy to fix by adapting code from os.walk, which is native python code built on top of os.listdir and os.path.isdir, rather than invoking os.walk directly.

With respect to the question of native capabilities versus external utilities, python is native to recent releases of MacOS. Where scripting like this ranks compared to pulling in external functionality is a matter of taste.

There might be an invocation of find which fits your criteria, similar to the ls pipeline in a comment, using the -type option in multiple invocations of find, but to me that feels clumsy compared to python code.