Git push to new repo from existing repo’s branch

Image for postProject setup to git push from my-project repository (repo) to new-project repo

While working with multiple projects, you might have encountered a situation where you need to create a new project from existing project?s (repo) some branch. We can always do it manually by copying and pasting and uploading it to new repo.

However, this is another ?better way? to achieve this, with the help of git itself.

Lets start by adding new remote repository into existing git project:

Go to current project: $ cd my-projectList current remote: $ git remote -vorigin (fetch)origin (push)Add new origin (origin2): git remote add origin2 <git_url>$ git remote add origin2 default, git uses origin, so lets add new origin as origin2)Lets see recently added origin: $ git remote -vorigin (fetch)origin (push)origin2 (fetch)origin2 (push)

Pushing ?master? branch to the new repository:

The following command pushes master branch of current repo to master branch of new repo with remote configured as origin2.$ git push <remote_name> <remote_repo_branch>$ git push origin2 master

Pushing specific branch:

The following command pushes specific branch (say dev) of current repo to master branch of new repo with remote configured as origin2.$ git push origin2 <source_branch>:<destination_branch>$ git push origin2 dev:masterUse –force (to forcefully push into that new branch if required)$ git push origin2 <source_branch>:<destination_branch> –force

Removing previous commits or tracking history of current repository:

If you want to push to the new repo without all the history of the existing repo, then you can create new orphan type branch which does not record previous history. Then push this new branch to our desired repo:

git checkout –orphan clean-branchAdd the files and commit:$ git add . && git commit -m “initial commit to new repo”

Push to new repository from the new clean-branch:

git push origin2 <source_branch>:<destination_branch>i.e;$ git push origin2 clean-branch:master

Note: You can push to origin2 from new clean-branch created locally and don?t need to push this new clean-branch to server.

Deleting branch:

You can delete the newly created local branch if you wish. Just checkout to a different branch than the one you want to delete and then delete using commands:

Checkout another branch:$ git checkout masterDelete the newly created branch:$ git branch -D clean-branch


No Responses

Write a response