π

Skipping Empty Directories In zsh

Show Sidebar

On GitHub, I started to love a nice feature I would like to have in my zsh as well. If I change to a directory that contains nothing but a single sub-directory, change to this sub-directory instead (recursive).

Therefore, when I am in a directory which contains the following sub-directories, I would like to skip all directories until there_is_a_file when I type cd dir_with_empty_subdirs:

You can try out this feature on GitHub in my test repo: simply click on the directory dir_with_empty_subdirs and you really going to end up in the directory there_is_a_file.

In case I need to visit any (almost empty) directory within this cascade, I can do so by going back via "cd .." which does not skip empty directories, thus avoiding an endless loop and non-visitable directories.

Well, I was not able to come up with a solution on my own. Reddit-user seanliao96 did provide a perfectly working solution:

function chpwd() {
    files=$(ls -A | wc -l)
    if [[ $files = "1" ]]; then
        zmodload zsh/parameter
        if [[ "cd .." != $history[$HISTCMD] ]]; then
            f=$(ls -A)
            if [[ -d "$f" ]]; then
                cd "$f"
            fi
        fi
    fi
}	  

Simply paste this code in your zsh or add it to your ~/.zshrc.local and enjoy the higher usability in your shell.

Comment via email (persistent) or via Disqus (ephemeral) comments below: