Using Git Hooks When Creating Worktrees

I’ve started to use git worktrees more lately but one of the pain points I had was that they don’t copied ignored files such as .env files. I found I was able to improve this workflow by adding a post-checkout hook.

In a nutshell, the hook will check if we are checking out a new worktree (that’s what the "$1" == "0000..." is all about). If we are, then we can run some code to copy over whatever files we need to.

.git/hooks/post-checkout
#!/bin/bash

if [[ "$1" == "0000000000000000000000000000000000000000" ]]; then
	basePath="$HOME/dev/repo"
	paths=(.env)

	for path in "${paths[@]}"; do
		cp "$basePath/$path" "$(pwd)/$path"
	done
fi