Conditional Content Listing on Directory Change

One of the most popular tweaks to the default Linux command line experience is to alias cd with cd && ls. I too had a variant of this in my .bashrc which went something like this:

builtin cd "$@" && pwd && ls -shF

Recently, however, I've been working in a directory with over 2000 files, and it seems a bit preposterous to list them all. My new alias is a bit more complex, but prevents my screen from being overwhelmed with file listings.

The first thing I do is add a conditional based upon the number of files in the directory.

if [ $(ls | wc -l) -lt 50];

I've set the cutoff at 50 for now, but it's easy enough to change. Anything under that threshold will display normally, but when we get into large collections it triggers this line:

else echo "$(ls -p | grep -v / | wc -l) files" && ls -d */ 2> /dev/null;

The first part (before the '&&') gives a count of non-directory files. Then it gives a listing of all subdirectories. Note I've also redirected the stderr (2>) to /dev/null because it would have otherwise displayed an error every time you navigate to a directory with no subdirectories.

Full .bashrc entry:

# CD also does PWD and LS

function cd {

builtin cd "$@" && pwd && if [ $(ls | wc -l) -lt 50 ]; then ls -s -h -F; else echo "$(ls -p | grep -v / | wc -l) files" && ls -d */ 2> /dev/null; fi


Made in Vim