Skip to content

Instantly share code, notes, and snippets.

@anonoz
Created February 1, 2026 09:50
Show Gist options
  • Select an option

  • Save anonoz/bd5836f079a875dc513286de0406398e to your computer and use it in GitHub Desktop.

Select an option

Save anonoz/bd5836f079a875dc513286de0406398e to your computer and use it in GitHub Desktop.
#!/bin/bash
# Git post-checkout hook to automatically copy environment files to new worktrees
# This hook runs after git checkout, git switch, and git worktree add
# CONFIGURATION: Modify these lists for your project
# Files to symlink (relative to repo root)
SYMLINK_FILES=(
".env"
".env.test"
)
# Files/directories to copy (relative to repo root)
COPY_FILES=(
"tmp/tunnel"
"tmp/cloudflared-config.yml"
)
# ============================================================================
prev_head="$1"
new_head="$2"
branch_checkout="$3"
# Check if this is a worktree creation (previous HEAD is null)
if [[ "$prev_head" == "0000000000000000000000000000000000000000" ]] && [[ "$branch_checkout" == "1" ]]; then
echo "πŸ”§ New worktree detected - setting up environment files..."
# Get the main repository path
main_repo_path="$(git rev-parse --git-common-dir)/.."
main_repo_path="$(cd "$main_repo_path" && pwd)"
# Get current worktree path
current_path="$(pwd)"
echo "πŸ“ Copying from: $main_repo_path"
echo "πŸ“ Copying to: $current_path"
# Create necessary directories from COPY_FILES
while IFS= read -r dir; do
if [[ ! -d "$current_path/$dir" ]]; then
mkdir -p "$current_path/$dir"
echo "πŸ“ Created $dir"
fi
done < <(printf '%s\n' "${COPY_FILES[@]}" | xargs -I {} dirname {} | sort -u)
# Symlink files
for file in "${SYMLINK_FILES[@]}"; do
if [[ -f "$main_repo_path/$file" ]]; then
ln -sf "$main_repo_path/$file" "$current_path/$file"
echo "βœ… Symlinked $file"
else
echo "⚠️ $file not found in main repository"
fi
done
# Copy files
for file in "${COPY_FILES[@]}"; do
source_file="$main_repo_path/$file"
target_file="$current_path/$file"
if [[ -f "$source_file" ]]; then
mkdir -p "$(dirname "$target_file")"
cp "$source_file" "$target_file"
echo "βœ… Copied $file"
else
echo "⚠️ $file not found in main repository"
fi
done
echo "πŸŽ‰ Environment setup complete for new worktree!"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment