Image

Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

How to programmatically determine which zsh startup file to set ZDOTDIR and XDG_CONFIG_HOME?

+0
−0

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 zshenv if I have write access (or sudo).
  • Fall back to the user’s ~/.zshenv otherwise.
  • 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
}
History

0 comment threads

Sign up to answer this question »