I want to record my most recent cd
across any one of my terminals. I thought a good way to do this would be to write a simple bash script wrapping cd
:
#!/bin/bash
cd $1 && echo `pwd` > /tmp/.cwd
Since I want the cd
to occur in my terminal's process, I need to run the script with . bettercd.sh
, correct?
Here comes my issue:
If I alias cd
to this new . bettercd.sh
, my shell also expands the cd
inside of the script with the . bettercd.sh
-- infinite recursion.
Is there any way to call cd
from a different name but with the same behavior? To put it another way, is there some command that behaves exactly (or very similar to) cd
that I can use in my shell script without noticing a difference when I use the aliased cd
day to day?
My shell of choice is zsh, if that's relevant in some way.
Thanks for your help.
zsh
provides thechpwd_functions
hook functions specifically for tools like this. If you define a function to append the new directory to a file and add the function to thechpwd_functions
array, it'll automatically run the routine every time it changed directory -- whether forpushd
popd
orcd
:In addition to already posted answers (I personally would prefer @sarnold’s one) you can use the fact that
chdir
in zsh has the same behavior ascd
, but is not an alias of the kind you can define withalias
(it may be an “alias” in C source code, I do not know) thus using it is safe.Since you are using zsh, you can use
builtin cd
in place ofcd
. This forces the shell to use the builtin command instead of recursively calling your alias.builtin
does not exist in standard bourne shell. If you need this to work in other shells, try prefixing cd with a backslash like this:\cd
. It works to bypass aliases but not shell functions.Inside your script call
cd
withbuiltin
:You could try putting
unalias cd
at the top of yourbettercd.sh
I'd suggest a different name to avoid exactly this happening - what if some other script does a CD - if it uses your version instead of "normal", that could play havock with the system.