Skip to content

Instantly share code, notes, and snippets.

@ssv445
Last active April 4, 2023 05:36
Show Gist options
  • Select an option

  • Save ssv445/739083f17c2f64ea744b29cfb2fdeed5 to your computer and use it in GitHub Desktop.

Select an option

Save ssv445/739083f17c2f64ea744b29cfb2fdeed5 to your computer and use it in GitHub Desktop.
Merge other branch into your current branch
#!/bin/bash
parent_branch="${1:-master}"
# Check if the current branch has any uncommitted changes
if [[ $(git status --porcelain) ]]; then
echo "Error: The current branch has uncommitted changes. Please commit or stash them before running this script."
exit 1
fi
# Get the name of the current branch
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
# Validate the specified parent branch name
if ! git show-ref --verify --quiet "refs/remotes/origin/$parent_branch"; then
echo "Error: Invalid parent branch name. Please enter a valid branch name."
exit 1
fi
# Fetch the latest changes from the remote $parent_branch branch
if ! git fetch origin $parent_branch; then
echo "Error: Failed to fetch changes from remote repository. Please check your network connection and try again."
exit 1
fi
# Merge the latest changes from the remote $parent_branch branch into the current branch
if git merge origin/$parent_branch --no-commit --no-ff; then
# If the merge was successful, commit the changes and push them to the remote repository
if ! git commit -m "Merge changes from $parent_branch branch"; then
echo "Error: Failed to commit changes. Please check if there are any conflicts or errors and try again."
exit 1
fi
if ! git push origin $CURRENT_BRANCH; then
echo "Error: Failed to push changes to remote repository. Please check your network connection and try again."
exit 1
fi
echo "Merge successful."
else
# If the merge resulted in conflicts, print an error message and exit
echo "Error: The merge resulted in conflicts. Please resolve the conflicts and commit the changes before running this script again."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment