ZSH: automatically run ls after every cd

Zsh

Zsh Problem Overview


So I've got ZSH doing all this cool stuff now, but what would be REALLY awesome is if I could get it to run 'ls -a' implicitly after every time I call 'cd'. I figure this must go in the .zlogin file or the .aliases file, I'm just not sure what the best solution is. Thoughts? Reference material?

Zsh Solutions


Solution 1 - Zsh

EDIT: After looking at documentation (zshbuiltins, description of cd builtin or hook functions) I found a better way: it is using either chpwd function:

function chpwd() {
    emulate -L zsh
    ls -a
}

or using chpwd_functions array:

function list_all() {
    emulate -L zsh
    ls -a
}
chpwd_functions=(${chpwd_functions[@]} "list_all")

Put the following into .zshrc:

function cd() {
    emulate -LR zsh
    builtin cd $@ &&
    ls -a
}

Solution 2 - Zsh

Short version.

autoload -U add-zsh-hook
add-zsh-hook -Uz chpwd (){ ls -a; }

Quick explanation of what's going on here.

autoload -U add-zsh-hook

This line basically just loads the contributed function add-zsh-hook.

add-zsh-hook -Uz chpwd (){ ls -a; }

Each of the special functions has an array of functions to be called when that function is triggered (like by changing directory). This line adds a function to that array. To break it down...

add-zsh-hook -Uz chpwd

This part specifies that we are adding a new function to the chpwd special function. The -Uz are generally the recommended arguments for this, they are passed to the autoload used for the function argument (ie. the next bit).

(){ ls -a; }

This second part is the function. It is what is generally referred to as an anonymous function. That is a function that hasn't been assigned a name. It doesn't need a name as it is just going in an array.

Solution 3 - Zsh

I don't know why this is the case or if this is better however I have found that this also works in .zshrc. Seems a lot shorted than most of the answers although maybe it is missing something I don't understand.

chpwd() ls -a

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondrmanitobaView Question on Stackoverflow
Solution 1 - ZshZyXView Answer on Stackoverflow
Solution 2 - ZshJohn EikenberryView Answer on Stackoverflow
Solution 3 - ZshRemakingEdenView Answer on Stackoverflow