Frustrated when your terminal forgets your last location? I’ve been there! After revamping my terminal, I ran into the same hiccup. Let’s sort this out with a quick fix and ensure iTerm2 always picks up right where you left off!
Before we get started, make sure you have the latest version!
You can read about my terminal makeover journey here.
Step 1: Setting Up the code
Command for Visual Studio Code
Fire up Visual Studio Code.
Hit
Cmd + Shift + P
to open the Command Palette.Type
Shell Command: Install 'code' command in PATH
and select it.Restart your terminal to lock in the changes.
Now, let’s crack open your
.zshrc
file with:
code ~/.zshrc
Step 2: Adding Some Magic to Your .zshrc
Scroll to the bottom of your .zshrc
and paste in this magic:
# Save the last directory on exit
function save_last_directory {
echo "$PWD" > ~/.last_directory
}
# Change to the last directory on startup
function load_last_directory {
if [ -f ~/.last_directory ]; then
cd "$(cat ~/.last_directory)"
fi
}
# Hook the save function to the prompt
autoload -Uz add-zsh-hook
add-zsh-hook chpwd save_last_directory
add-zsh-hook precmd save_last_directory
# Load the last directory on shell startup
load_last_directory
Step 3: Save, Apply, and Chill
Save your changes (press
⌘ + S
).Run this command to bring your changes to life:
source ~/.zshrc
Boom! Now your terminal will remember where you left off, every single time.
Hold up! Still having issues? 🤔
Did you check iTerm2 Settings → Profiles → Working Directory and make sure “Reuse previous session’s directory” is enabled? Let’s make sure everything’s set up right! 🚀
Double Boom! No more starting from scratch. Enjoy your newfound terminal superpowers!