Rebuilding my dotfiles with GNU Stow
My dotfiles repo had been sitting mostly untouched for a couple of years, with old configs for nvim, tmux and bash, and an install script per tool that ran ln -sfv for every file it knew about. The cleanup I started turned into a rewrite, so this post goes through what changed and why, mostly as notes for the next time I set up a machine. The repo is public, it's used on macOS and on Fedora, and a good part of the commands in my terminal are typed by coding agents these days, so the shell has to work for them as well as for me.
From ln -sfv to Stow
The old setup looked like this, one script per tool, each one kept in sync with the files in the repo by hand:
mkdir -p "$ZDOTDIR" ln -sfv "$DOTFILES"/zsh/zshenv "$HOME"/.zshenv ln -sfv "$DOTFILES"/zsh/zshrc "$ZDOTDIR"/.zshrc ln -sfv "$DOTFILES"/zsh/dircolors "$ZDOTDIR"/dircolors GNU Stow removes that whole category of script. Each top level folder in the repo is a "package" that mirrors ~, so zsh/.zsh/.zshrc gets linked to ~/.zsh/.zshrc, ghostty/.config/ghostty/config.ghostty to ~/.config/ghostty/config.ghostty, and so on. To add a config file, you put it at the right path inside a package and run stow again, and there is no list of files to maintain anywhere.
The options live in a .stowrc at the root of the repo, which stow reads from the current directory:
--target=~ --no-folding --ignore=\.DS_Store --no-folding is the option I'd copy first. By default stow "folds" a folder, which means that if ~/.zsh doesn't exist yet, it creates ~/.zsh as a single link to the repo's folder instead of a real folder with links to the files in it. That sounds tidy, but then every file an app writes next to its config (zsh history, the completion dump, caches) lands inside the repo, and ~/.ssh becomes a link with whatever permissions the repo folder has. With --no-folding stow links individual files, so ~/.zsh, ~/.ssh and ~/.config/* stay real folders. It's still a good idea to list those machine-local files in .gitignore, in case a folding ever happens by accident.
The linking step is now a single stow call (plus some checks for leftovers from the old layout), and it picks the per-OS git package:
[[ $OSTYPE == darwin* ]] && os_git=git-macos || os_git=git-linux cd "$DOTFILES" || return 1 stow --restow shell zsh git ghostty mise ssh espanso zed starship claude "$os_git" || return 1 Stow also refuses to replace a real file or a link it didn't make, which is what we want on a fresh Fedora install, where /etc/skel has already put a .bashrc and .bash_profile in the home folder, so the installer moves those aside to *.pre-dotfiles before stowing.
One PATH file for every shell
Tool versions now come from mise for Node, Terraform and the global npm CLIs, through its shims rather than mise activate, since activation made every shell start noticeably slower and direnv already covers the per-project environment. The plan was to drop rbenv too and let mise handle Ruby, but a public open-source project I work with calls rbenv directly from its git hooks and make init, so rbenv came back and owns Ruby only, with Ruby disabled in mise.
With the shims in place PATH looked right in an interactive zsh, so I assumed it was done (it wasn't). zsh -lc, which is how Codex and a lot of other tools run commands, and bash both found the wrong node. The reason is macOS's /etc/zprofile, which runs path_helper after ~/.zshenv in every login shell and moves the system folders back in front of whatever we put there, along with Homebrew when /etc/paths.d lists it (it does on my Mac).
What fixed it is one POSIX sh file, ~/.config/shell/path.sh, which ~/.zshenv, ~/.zsh/.zprofile, ~/.profile and ~/.bashrc all source. .zprofile sources it a second time on purpose, after path_helper has had its turn:
#!/bin/zsh # Login shells only. macOS's /etc/zprofile runs path_helper after .zshenv and moves the system and Homebrew # folders back in front of the shims; reapply them so `zsh -lc` (agents, Codex) gets the project's node and ruby. . "$HOME/.config/shell/path.sh" Sourcing the same file more than once means it can't just prepend, or PATH grows with every nested shell. zsh has typeset -U path for that, but bash doesn't, so the file has a small helper that moves a folder to the front and removes any earlier copy of it. Here it is, with the cargo and bun lines left out:
_path_front() { PATH=":$PATH:" while case $PATH in *":$1:"*) true ;; *) false ;; esac; do PATH="${PATH%%:"$1":*}:${PATH#*:"$1":}" done PATH="${PATH#:}" PATH="${PATH%:}" # No trailing ":" when nothing else is left: an empty PATH entry means the current directory PATH="$1${PATH:+:$PATH}" } if [ -d /opt/homebrew/bin ]; then _path_front /opt/homebrew/sbin _path_front /opt/homebrew/bin fi _path_front "${XDG_DATA_HOME:-$HOME/.local/share}/mise/shims" _path_front "$HOME/.rbenv/shims" _path_front "$HOME/.local/bin" unset -f _path_front export PATH The first version ended with PATH="$1:$PATH", which looks harmless, but when PATH starts out empty (or holds only the folder being moved) it leaves a trailing :, and an empty entry in PATH means the current folder. You never see that in a normal shell, and it took a test that sources the file from an empty PATH to show it, which is why the last line uses ${PATH:+:$PATH} now.
Homebrew is added by path rather than with brew shellenv for two reasons. Apps launched from the Dock start with only /usr/bin:/bin:/usr/sbin:/sbin, so whatever they start (a terminal, an editor running an agent) gets Homebrew from path.sh without running any program, and brew shellenv would push Homebrew back in front of the shims, so Homebrew's node would win over the project's. Apps that read the login shell's environment (Claude Desktop, VS Code based editors) do that once when they start, so after changing PATH you have to restart them.
Add new PATH entries in one file, nowhere else. With a single file, zsh -c, zsh -lc, bash -lc and sh -lc all find the same tools, and there's one place to look when they don't.
A shell that coding agents can use
Agents that drive an interactive terminal (Cursor and other editor agents) run into a few interactive niceties. zsh's spelling correction stops and asks zsh: correct 'foo' to 'fo' [nyae]?, git opens a pager and waits for q, and aliases like ls to eza or rm -i either break flags the agent expects or prompt for input nobody will type. The tools set environment variables we can check for (Codex only inside its sandbox), so .zshrc turns those things off for them:
# Claude Code sets AI_AGENT/CLAUDECODE, Cursor CURSOR_AGENT, Codex CODEX_SANDBOX; add others here. [[ -n $AI_AGENT$CLAUDECODE$CURSOR_AGENT$CODEX_SANDBOX ]] && typeset -g AGENT_SHELL=1 if (( AGENT_SHELL )); then unsetopt CORRECT export PAGER=cat GIT_PAGER=cat fi and aliases.zsh wraps the human-only aliases in if (( ! AGENT_SHELL )); then ... fi. Commands run with zsh -lc never read .zshrc, so they don't need any of this, and they get their PATH from .zshenv and .zprofile as above.
The other change is the shell Claude Code's Bash tool uses. Agents write bash, and zsh doesn't split an unquoted $VAR into words, so something like rm $files gets the whole list as a single argument and fails in a confusing way. Claude Code reads CLAUDE_CODE_SHELL, and macOS's /bin/bash is still 3.2, so .zshenv points it at a newer bash:
if [[ -x /opt/homebrew/bin/bash ]]; then export CLAUDE_CODE_SHELL=/opt/homebrew/bin/bash elif [[ -x /usr/bin/bash ]]; then export CLAUDE_CODE_SHELL=/usr/bin/bash fi That bash sources ~/.bashrc, which sources path.sh, so it ends up with the same PATH as everything else.
Keeping identities and secrets out of a public repo
Over the years the git config had picked up identity rules from older setups, includeIf "gitdir:..." and includeIf "hasconfig:remote.*.url:..." blocks that pick the name, email and signing key for a repo by its folder or its remote, and the ssh config had host aliases with their keys to match. It's useful config, but in a public repo it's personal detail nobody else needs, so the rules moved to local files and the tracked config only keeps the mechanism. Git skips an include whose file doesn't exist, so the tracked config can point at an untracked file and still work on a machine that doesn't have it (where you get the default identity, so copy the local files in before committing anything that needs another one):
# Default identity; identities.gitconfig below overrides it per directory or remote [include] path = ~/.config/git/personal.gitconfig # Which identity a repo gets, by folder or by remote URL: includeIf rules in this local, untracked file. # Included last so its rules override personal.gitconfig; git skips it when it doesn't exist. [include] path = ~/.config/git/identities.gitconfig ssh does the same with one line at the top of the tracked config, Include config.d/*, which is fine with an empty or missing folder, and zsh sources ~/.zsh/zshenv.local and ~/.zsh/aliases.local.zsh only if they exist. The local files are kept in 1Password, so a new machine gets them by copying them in before running the installer. An older commit that I hadn't pushed yet still had some of the old identity config in it, and since the remote had never seen it, a git rebase -i origin/master that dropped that commit was enough, with nothing to force-push.
While cleaning up the ssh config I almost removed the .pub files too, on the reasoning that the private keys live in 1Password and the agent serves them anyway. That's wrong, because the 1Password agent offers every key in the vaults it's set up to use, GitHub logs you in as whichever account the first accepted key belongs to, and with several keys loaded that can be the wrong account. Pointing IdentityFile at the public key and setting IdentitiesOnly stops it, since ssh then only offers that one key from the agent:
Host github.com HostName github.com User git IdentityFile ~/.ssh/github_personal.pub IdentitiesOnly yes For secrets there's a gitleaks pre-commit hook. Zed's settings UI writes API keys straight into settings.json, which is linked into this repo, so the hook scans every staged change for anything that looks like a key or token:
repos: - repo: local hooks: - id: gitleaks name: gitleaks (staged changes) entry: gitleaks git --pre-commit --staged --redact --verbose language: system pass_filenames: false The hook only exists in a clone after pre-commit install, so it's a good idea to try committing a fake token-shaped string (ghp_ and 36 random characters, never a real token) once to see it blocked. The Zed MCP servers get their keys from op:// references (I wrote about those in Using 1Password secret references for MCP server credentials), so the real values never touch the file, and the servers are pinned to exact versions instead of latest, since they run with those keys.
Testing the shell functions
The last piece is test/smoke.sh, which I run before committing. It checks the syntax of every zsh and sh file, runs shellcheck on the sh ones and does a stow dry run (when shellcheck and stow are installed), and probes the most used shell functions with a stubbed fzf, in a temporary folder with a space in a path inside it. A test only proves something once you've seen it fail on the bug it's meant to catch (more on that in Writing checks that can fail on the bug they guard against), so the probes for the bugs below were each run against the old version of the file too.
fwr, which removes git worktrees, broke on paths with spaces, because zsh splits an unquoted $(...) nested inside ${...}, so ${$(cmd):h} breaks where ${"$(cmd)":h} doesn't. extract had stopped handling .Z files after a ${1:l} was added to lower-case the file name, since the *.Z pattern could never match anymore. And that probe skipped its step without saying so at first, because compress leaves a file alone if compressing would make it bigger, which a tiny test file does, so it needs -f. The path.sh check, the one that caught the empty PATH entry, sources the file from an empty PATH, from one holding only a folder it moves, and from one with duplicates, and fails on an empty entry, a duplicate, or a different result when sourced twice.
Summary
For a dotfiles repo, Stow with --no-folding does what the old install scripts did, without the list of files to maintain and without apps writing into the repo. PATH belongs in one POSIX file that every shell sources, and on macOS login shells it has to be applied again after path_helper, which is easy to miss because an interactive shell looks fine. Coding agents use the shell too, and a couple of environment variables are enough to turn off the prompts and pagers they can't get past, while CLAUDE_CODE_SHELL gives Claude Code bash where it expects bash. In a public repo, identity config (which name, email and key goes with which repo) belongs in local files that the tracked config includes, which git, ssh and zsh all support, and it's far less work to move it there before the first push.
原文:https://www.a8q9.cn/en/article/rebuilding-my-dotfiles-with-gnu-stow-1b835c.html