ZSH: automatically run ls after every cd
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?
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
}
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.