zsh provides some nice 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
andpopd
) - 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
ifextdebug
is enabled and the trap function returns 1, but I don't think I want to forceextdebug
, and returning1
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?
cd
,pushd
, andpopd
? How many other ways are there to change directory?cd
as a principle.MYBIN=$( cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P )
Please do not change the trusted Unix commands.bash
, which works pretty much the same on all operating systems that it runs on.