Infinite recursion aliasing `cd`

I want to record the latest cd through any of my terminals. I thought a good way to do this is to write a simple bash script wrapping cd :

 #!/bin/bash cd $1 && echo `pwd` > /tmp/.cwd 

Since I want cd execute in my terminal process, I need to run the script with . bettercd.sh . bettercd.sh , right?

Here is my problem: If I add cd to this new one . bettercd.sh . bettercd.sh , my shell also extends cd inside the script with . bettercd.sh . bettercd.sh - infinite recursion.

Is there a way to call cd from a different name but with the same behavior? In other words, is there some kind of command that behaves exactly (or very similar to) cd that I can use in my shell script without noticing the difference when I use the alias cd day after day?

My shell of choice is zsh, if that matters in some way.

Thanks for your help.

+1
source share
6 answers

Since you are using zsh, you can use builtin cd instead of cd . This forces the shell to use the built-in command instead of recursively invoking your alias.

builtin does not exist in the standard bourne shell. If you need this to work in other shells, try the cd prefix using the backslash as follows: \cd . It works to bypass aliases, but not for shell functions.

+6
source

zsh provides chpwd_functions binding chpwd_functions specifically for such tools. If you define a function to add a new directory to a file and add a function to the chpwd_functions array, it will automatically run this procedure every time the directory is changed - 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 $ 
+5
source

Inside your cd script call using builtin :

 #!/bin/bash builtin cd $1 && echo `pwd` > /tmp/.cwd 
+2
source

In addition to the answers already posted (I personally would prefer @sarnolds one), you can use the fact that chdir in zsh has the same behavior as cd but is not an alias of the type you can define with alias (this there may be an β€œalias” in the C source code, I don’t know), so its use is safe.

+2
source

You can try placing unalias cd at the top of bettercd.sh

0
source

I would suggest a different name to avoid this. What if any other script makes a CD - if it uses your version instead of the "normal" one, which can play a hawk with the system.

0
source

All Articles