Skip to content

Instantly share code, notes, and snippets.

@disafronov
Last active December 20, 2025 11:17
Show Gist options
  • Select an option

  • Save disafronov/9c0bf73a6cd26aa5324c76b7ab459e8c to your computer and use it in GitHub Desktop.

Select an option

Save disafronov/9c0bf73a6cd26aa5324c76b7ab459e8c to your computer and use it in GitHub Desktop.
Sync one's ~/.dotfiles with git & stow
#!/usr/bin/env sh
set -eu
# Base directory for dotfiles repository
REPO_DIR="$HOME/.dotfiles"
# Determine action (pull or push) and flags
ACTION=""
FORCE=""
for arg in "$@"; do
case "$arg" in
-f|--force)
FORCE="1"
;;
pull|push)
ACTION="$arg"
;;
esac
done
if [ "$ACTION" = "pull" ]; then
if [ "$FORCE" = "1" ]; then
# Forcefully sync local repository history and working tree with upstream
git -C "$REPO_DIR" fetch || exit 1
git -C "$REPO_DIR" reset --hard @{u} || exit 1
git -C "$REPO_DIR" clean -fdx || exit 1
else
# Pull the latest files from git
git -C "$REPO_DIR" pull || exit 1
fi
# Save current working directory
OLDPWD="$PWD"
# Change into repository directory
cd "$REPO_DIR" || exit 1
# Remove old stow links safely (if any)
stow -D . 2>/dev/null || true
# Apply stow links
stow . || exit 1
# Return to original working directory
cd "$OLDPWD" || exit 1
elif [ "$ACTION" = "push" ]; then
# Add, commit and push all files
git -C "$REPO_DIR" add -A || exit 1
# Commit if there are staged changes
if ! git -C "$REPO_DIR" diff --cached --quiet; then
git -C "$REPO_DIR" commit -m "chore: update" || exit 1
fi
if [ "$FORCE" = "1" ]; then
# Forcefully overwrite remote history with local branch
git -C "$REPO_DIR" push --force || exit 1
else
# Ensure upstream is configured and fail loudly if there is nothing to push
git -C "$REPO_DIR" rev-parse --abbrev-ref --symbolic-full-name @{u} >/dev/null 2>&1 || exit 1
if git -C "$REPO_DIR" rev-list @{u}..HEAD --quiet; then
git -C "$REPO_DIR" push || exit 1
else
exit 1
fi
fi
else
echo "Usage: $0 {pull|push} [-f|--force]" >&2
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment