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.
Since you are using zsh, you can use builtin cd
in place of cd
. 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.
zsh
provides the chpwd_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 the chpwd_functions
array, it'll automatically run the routine every time it changed directory -- whether for pushd
popd
or cd
:
$ record_pwd() { pwd > /tmp/cwd }
$ chpwd_functions=(record_pwd)
$ cd /tmp ; cat /tmp/cwd
/tmp
$ cd /etc ; cat /tmp/cwd
/etc
$
Inside your script call cd
with builtin
:
#!/bin/bash
builtin cd $1 && echo `pwd` > /tmp/.cwd
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 as cd
, but is not an alias of the kind you can define with alias
(it may be an “alias” in C source code, I do not know) thus using it is safe.
You could try putting unalias cd
at the top of your bettercd.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.