Skip to content

Instantly share code, notes, and snippets.

@unphased
Created May 2, 2025 03:49
Show Gist options
  • Save unphased/4e4a46f0f497359430f18d6874fbbff6 to your computer and use it in GitHub Desktop.
Save unphased/4e4a46f0f497359430f18d6874fbbff6 to your computer and use it in GitHub Desktop.
Undo n recent commits, or to a specified hash. Easy terminal ux to specify drop or revert (revert will make the undo show in history as a new commit, drop drops those commits)
#!/bin/bash
set -e
# Check for uncommitted changes
if ! git diff --quiet HEAD --; then
echo "Error: Uncommitted changes detected in the working directory or index." >&2
echo "Please commit or stash your changes before running git-undo." >&2
exit 1
fi
default_target="HEAD~1"
# Determine the target based on $2
if [ -z "$2" ]; then
# $2 is empty, use default
target="$default_target"
elif [[ "$2" =~ ^[0-9]+$ ]]; then
# $2 is a number N, use HEAD~N
target="HEAD~$2"
else
# $2 is not a number, use it directly as commit-ish
target="$2"
fi
if [ "$1" = "drop" ]; then
echo "Resetting to $target"
git reset --hard "$target"
elif [ "$1" = "revert" ]; then
echo "Reverting commits from $target..HEAD"
git revert --no-commit "$target"..HEAD
git commit -m "Revert commits from $target..HEAD"
else
echo "Usage: git-undo [drop|revert] [<target>]"
echo " <target> can be a commit hash, tag, branch, HEAD~N, or just N (defaults to 1, meaning HEAD~1)"
# Indicate failure for incorrect usage
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment