A friend of mine used ZSH on his Mac and since I know him and his .zshrc, I keep ZSH as the main CLI on my laptop, it works so well, I advise you to switch if still not 😛 .

But, I was very tired of typing a long cd command every time I wanted to open a new Terminal tab to execute a command in the same directory or close to where I was working; so I looked for a hack to get rid of this pain over the Internet and now, I'd like to share it with you.

The solution is to overload the cd() function and add a custom script inside. The problem of retrieving the current pwd is irrelevant if you are in the same TTY because you could navigate through your directory history with cd - or even pushd, popd and dirs.
But when you open a new window/tab, the new TTY doesn't handle your navigation history. The idea is to keep the last current working directory (I shortened it as cwd) in a file and make an alias to change the working dir to this saved path :

Copy/paste the following code into your console to install and enable the very useful hack:

cat << SOURCE >> ~/.zshrc

# Function to switch and save the current path
function cd() {
  builtin cd "$@";
  echo "$PWD" > ~/.cwd;
export cd
alias cwd='cd "$(cat ~/.cwd)"'
. ~/.zshrc

Okay, if you try new the alias command cwd without any cd before, you might have an error because the file ~/.cwd doesn't exist yet.
Try out a cd command and open a new window or tab and type cwd.

Perfect isn't it?


If you want your Terminal to remind the last working path, you just have to add a cwd command at the end of you .zshrc file :

echo "\ncwd" >> ~/.zshrc
. ~/.zshrc


Joris Berthelot