bashzshcdcwd

Is there a hook in Bash to find out when the cwd changes?


I am usually using zsh, which provides the chpwd() hook. That is: If the cwd is changed by the cd builtin, zsh automatically calls the method chpwd() if it exists. This allows to set up variables and aliases which depend on the cwd.

Now I want to port this bit of my .zshrc to bash, but found that chpwd() is not recognized by bash. Is a similar functionality already existing in bash? I'm aware that redefining cd works (see below), yet I'm aiming for a more elegant solution.

function cd()
{
    builtin cd $@
    chpwd
}

Solution

  • You would have to use a DEBUG trap or PROMPT_COMMAND.

    Examples:

    trap chpwd DEBUG        # calls the function before each command
    
    PROMPT_COMMAND=chpwd    # calls the function after each command
    

    Note that the function defined in PROMPT_COMMAND is run before each prompt, though, even empty ones.