Skip to content

Instantly share code, notes, and snippets.

@meteoFurletov
Created September 19, 2025 15:18
Show Gist options
  • Select an option

  • Save meteoFurletov/ea930b28a7aeddffc3c7bfb2b411a906 to your computer and use it in GitHub Desktop.

Select an option

Save meteoFurletov/ea930b28a7aeddffc3c7bfb2b411a906 to your computer and use it in GitHub Desktop.
#!/bin/bash
# A script to commit changes to a specific branch, then merge it back.
# Creates the branch if it doesn't exist, or uses it if it already exists.
# Ensures we're working with the latest version by pulling first.
# Exit immediately if any command fails
set -e
# --- VALIDATION ---
# Check if the correct number of arguments are provided
if [ "$#" -ne 2 ]; then
echo "❌ Error: You must provide a branch name and a commit message."
echo "Usage: git flow <branch-name> \"<commit-message>\""
exit 1
fi
SELECTED_BRANCH=$1
COMMIT_MESSAGE=$2
# --- HELPER FUNCTION ---
# Function to check if branch exists locally
branch_exists() {
local branch=$1
git branch --list "$branch" | grep -q "^[[:space:]]*$branch$"
}
# --- SCRIPT LOGIC ---
echo "▶️ Starting the automated Git process..."
# 1. Capture the current branch name
PREVIOUS_BRANCH=$(git rev-parse --abbrev-ref HEAD)
echo "✅ Current branch is '$PREVIOUS_BRANCH'."
# 2. Pull latest changes for the current branch
echo "🔄 Pulling latest changes for '$PREVIOUS_BRANCH'..."
git pull origin "$PREVIOUS_BRANCH" || echo "⚠️ Pull failed or no upstream set, continuing..."
# 3. Stage all changes
echo "➕ Staging all changes..."
git add .
# 4. Check if branch exists, create if not, then switch to it
if branch_exists "$SELECTED_BRANCH"; then
echo "🔄 Switching to existing branch '$SELECTED_BRANCH'..."
git switch "$SELECTED_BRANCH"
echo "🔄 Pulling latest changes for '$SELECTED_BRANCH'..."
git pull origin "$SELECTED_BRANCH" || echo "⚠️ Pull failed or no upstream set, continuing..."
else
echo "🆕 Creating and switching to new branch '$SELECTED_BRANCH'..."
git switch -c "$SELECTED_BRANCH"
fi
# 5. Commit and push
echo "📝 Committing with message: \"$COMMIT_MESSAGE\""
git commit -m "$COMMIT_MESSAGE"
echo "🚀 Pushing to origin '$SELECTED_BRANCH'..."
git push origin "$SELECTED_BRANCH" 2>/dev/null || git push --set-upstream origin "$SELECTED_BRANCH"
# 6. Switch back, pull latest, merge, and push
echo "🔄 Switching back to '$PREVIOUS_BRANCH'..."
git switch "$PREVIOUS_BRANCH"
echo "🔄 Pulling latest changes before merge..."
git pull origin "$PREVIOUS_BRANCH" || echo "⚠️ Pull failed or no upstream set, continuing..."
echo "🔗 Merging '$SELECTED_BRANCH' into '$PREVIOUS_BRANCH'..."
git merge "$SELECTED_BRANCH" --no-ff -m "Merge branch '$SELECTED_BRANCH'"
echo "🚀 Pushing merge to origin..."
git push
echo "🎉 Success! Workflow complete."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment