Infinite recursion aliasing `cd`

2019-07-26 04:27发布

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.

6条回答
Root(大扎)
2楼-- · 2019-07-26 04:39

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
$ 
查看更多
Explosion°爆炸
3楼-- · 2019-07-26 04:42

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.

查看更多
小情绪 Triste *
4楼-- · 2019-07-26 04:49

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.

查看更多
我只想做你的唯一
5楼-- · 2019-07-26 04:51

Inside your script call cd with builtin:

#!/bin/bash
builtin cd $1 && echo `pwd` > /tmp/.cwd
查看更多
手持菜刀,她持情操
6楼-- · 2019-07-26 04:53

You could try putting unalias cd at the top of your bettercd.sh

查看更多
贪生不怕死
7楼-- · 2019-07-26 04:53

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.

查看更多
登录 后发表回答