How to set the working directory as the tab title in Terminal for Mac

command lineterminalzsh

One of my Macs is running Mac OS Mojave and so for parity with my Catalina machine I switched the shell to zsh. Not sure exactly when but at some point I noticed the current working directory was never being displayed either in the prompt itself or in the title of the tab.

I found I way to restore the title to the prompt by adding this to my ~/.zprofile file: PROMPT='%~ '. However, I have not been able to restore the directory name to the tab title:

Terminal window with tabs

This is quite frustrating when dealing with multiple tabs, as I do daily. It would seem to me that everything in the Terminal's settings is correct:

Terminal Preferences

Am I missing something or have I encountered a strange bug?

Best Answer

Solution: Copy the zsh setup files (/etc/zshrc and /etc/zshrc_Apple_Terminal) from a Catalina system to the older system (preferably after backing up the original equivalent(s)).

I haven't tested this in Mojave, but I did in High Sierra, and it works fine there.

Explanation of the problem: Setting the Terminal window/tab title requires running some code (e.g. a shell function) to send the appropriate escape sequences, encoded version of the directory name, etc to the Terminal. In older versions of macOS, this was handled in bash by having /etc/bashrc run /etc/bashrc_Apple_Terminal, which defined a suitable function and set PROMPT_COMMAND to tell bash to run it each time it prompted for a new command. But since zsh wasn't the default shell, Apple didn't bother to create the equivalent setup scripts for zsh.

In Catalina, zsh is the default shell, so they wrote analogous setup steps and added them to /etc/zshrc and /etc/zshrc_Apple_Terminal. The mechanics are different (for example, zsh uses add-zsh-hook precmd instead of the PROMPT_COMMAND variable), but it does essentially the same thing. These files are not dependent on anything in Catalina; you can simply copy them to older systems, and they should work the same as they do in Catalina.