Failing to evaluate correct path to zshrc file on new terminal window/tab

76 Views Asked by At

I'm trying to set up dotfiles/config, which I will be storing in github and using across multiple devices.

One of the things I want to achieve is that no matter where I clone my dotfiles, once I source it I will automatically have aliases like updateDotfiles that will pull the latest changes.

In order to achieve this, I tried putting export DOTFILES_PATH=${0:P:h} into my .zshrc so that I can automatically detect the path to my dotfiles folder.

This works exactly how I want it to if I run source ~/.zshrc (which is a symlink). What I've noticed is that when I first open a new terminal tab/window, ${0:P:h} resolves to the wrong location. If I remove :h from it and echo the result I get /Users/me/-zsh and then if I run source ~/.zshrc I get /Users/me/dotfiles-and-utils/.zshrc

Is there something I'm missing here? How do I get it to work for both new windows and individual source runs?

In case it's relevant, I'm using iTerm2 and oh-my-zsh

2

There are 2 best solutions below

0
FlinnBurgess On BEST ANSWER

I came across the following Q&A which set me off in the right direction (I won't pretend to understand what it's doing exactly) https://unix.stackexchange.com/questions/249606/get-full-path-of-current-zsh-startup-file-e-g-zshrc-or-zshenv

Using ChatGPT I managed to tweak it to work how I wanted, the solution was to use DOTFILES_PATH=$(dirname $(realpath ${(%):-%N}))

realPath resolves any symlinks you have set up

In my case I wanted the directory I was storing my zshrc file, hence the use of dirname

2
user1934428 On

The zsh dotfiles are always looked up inside your $HOME, except if the variable ZDOTDIR is set. Hence you can find your dotfiles in ${ZDOTDIR:-$HOME} and don't need to fiddle with $0.

The border case, which this would not catch, happens, if you modify ZDOTDIR somehow inside your dotfiles. But it would be insane to do this anyway, since ZDOTDIR must be defined at the time the zsh is started, so a later change wouldn't make sense anyway.