How to programmatically determine which zsh startup file to set ZDOTDIR and XDG_CONFIG_HOME?
I want to configure zsh to read its config from ~/.config/zsh by setting ZDOTDIR=$XDG_CONFIG_HOME/zsh and ensuring XDG_CONFIG_HOME is defined early. Currently my script appends exports to three global files (/etc/profile, /etc/zshenv, /etc/zsh/zshenv) if I have sudo, otherwise symlinks ~/.zshenv.
Which files are actually needed for zsh? From the zsh manpage, only zshenv is always sourced for every zsh invocation. /etc/profile is for Bourne‑compatible shells, not zsh. Also, /etc/zshenv is the standard global file; /etc/zsh/zshenv appears only on some distributions (e.g., Debian derivatives).
How can I programmatically detect the correct file(s) to modify, instead of blindly writing to three locations? I’d like to:
- Prefer the global
zshenvif I have write access (or sudo). - Fall back to the user’s
~/.zshenvotherwise. - Avoid touching irrelevant files like
/etc/profile.
What is a reliable, cross‑distribution way to determine which path is the effective global zshenv and whether it should be used?
append_zshenv_to_global_files() {
if ! [ -e /etc/zshenv ]; then
sudo tee -a /etc/profile /etc/zshenv /etc/zsh/zshenv &>/dev/null <<EOF
export XDG_CONFIG_HOME=$XDG_CONFIG_HOME
export ZDOTDIR=$ZDOTDIR
EOF
fi
}
link_zshenv_to_home_directory() {
ln -s "$ZSHENV" "$HOME"/.zshenv
}
load_zshenv_on_startup() {
if has_sudo; then
append_zshenv_to_global_files
else
link_zshenv_to_home_directory
fi
}

0 comment threads