Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite recursion aliasing `cd`

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.

like image 343
bkase Avatar asked May 17 '26 05:05

bkase


1 Answers

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.

like image 164
Celada Avatar answered May 18 '26 22:05

Celada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!