Sample Header Ad - 728x90

How can I run a command in bash after any change in $PWD?

13 votes
3 answers
2843 views
zsh provides some nice [hook functions](http://zsh.sourceforge.net/Doc/Release/Functions.html#Hook-Functions) , including chpwd for running a function after the user changes directories. # zsh only function greet() { echo 'hi'; } chpwd_functions+=("greet") cd .. # hi pushd # hi popd # hi I'm trying to emulate that in bash. Constraints: - It must work in both interactive and non-interactive shells, which I think means that it can't rely on something like $PROMPT_COMMAND - It can't redefine cd, because I want it to work for any command that changes directories (eg, pushd and popd) - It must run *after* the user's command, so trap "my_function" DEBUG doesn't work, unless I can somehow say in there, "first run the $BASH_COMMAND we trapped, then also do this..." I see that I can avoid the automatic running of $BASH_COMMAND **if** extdebug is enabled **and** the trap function returns 1, but I don't think I want to force extdebug, and returning 1 for a successful (but modified) command seems wrong. The last part - "run after the user's command" - is what currently has me stumped. If I **can** run a function after each command, I can have it check whether the directory has changed since we last checked. Eg: function check_pwd() { # true in a new shell (empty var) or after cd if [ "$LAST_CHECKED_DIR" != "$PWD" ]; then my_function fi LAST_CHECKED_DIR=$PWD } Am I on the right track, or is there a better way? **How can I run a command in bash after the user changes directories?**
Asked by Nathan Long (1683 rep)
Dec 6, 2014, 03:25 AM
Last activity: Aug 31, 2020, 08:39 PM