Skip to content

Instantly share code, notes, and snippets.

@banyudu
Last active November 4, 2025 08:57
Show Gist options
  • Select an option

  • Save banyudu/ed874e8011366c755288579e4cded35b to your computer and use it in GitHub Desktop.

Select an option

Save banyudu/ed874e8011366c755288579e4cded35b to your computer and use it in GitHub Desktop.
Git merge-info command
#!/usr/bin/env bash
# ------------------------------------------------------------
# git-merge-into
# ------------------------------------------------------------
#
# Merge the current branch into the target branch without
# ever leaving the target branch checked out.
#
# Usage:
# git merge-into <target‑branch> [git‑merge‑options]
#
# Example:
# git merge-into develop --no-ff # merge the current branch into develop
#
# The script:
# 1. remembers your current branch,
# 2. ensures the target branch exists locally (fetches it if necessary),
# 3. checks out the target,
# 4. performs the merge, forwarding any extra flags,
# 5. returns you to the original branch.
#
# It works on macOS (zsh or bash) because the shebang points to
# /usr/bin/env bash – zsh can execute that just fine.
# ------------------------------------------------------------
set -e # exit immediately on error
# ---------- help -------------------------------------------------
if [[ $# -eq 0 || "$1" == "-h" || "$1" == "--help" ]]; then
cat <<'EOF'
Usage: git merge-into <target-branch> [merge options]
Merges the current branch into the specified target branch without
leaving the target branch checked out. Any options after the target
branch are passed straight to `git merge`.
Examples
git merge-into develop # merge current branch into develop
git merge-into master --no-ff # merge with a no‑fast‑forward merge
EOF
exit 0
fi
# ---------- parse arguments --------------------------------------
TARGET_BRANCH="$1"
shift # all remaining args are merge flags
# ---------- remember where we are -------------------------------
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
# ---------- make sure target branch exists ----------------------
if ! git show-ref --verify --quiet "refs/heads/$TARGET_BRANCH"; then
echo "Target branch '$TARGET_BRANCH' not found locally."
echo "Attempting to fetch it from 'origin'..."
git fetch origin "$TARGET_BRANCH":"$TARGET_BRANCH" || {
echo "❌ Could not fetch branch '$TARGET_BRANCH' from origin." >&2
exit 1
}
fi
# ---------- checkout target ------------------------------------
git checkout "$TARGET_BRANCH"
# ---------- merge -----------------------------------------------
echo "Merging branch '$CURRENT_BRANCH' into '$TARGET_BRANCH'..."
git merge "$CURRENT_BRANCH" "$@"
# ---------- return to original branch ---------------------------
git checkout "$CURRENT_BRANCH"
echo "✅ Merge complete. Back on branch '$CURRENT_BRANCH'."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment