Sometimes, Git can’t make your change to a remote repository without losing commits. When this happens, your push is refused.
If another person has pushed to the same branch as you, Git won’t be able to push your changes:
$ git push origin main
> To https://github.com/USERNAME/REPOSITORY.git
> ! [rejected] main -> main (non-fast-forward)
> error: failed to push some refs to 'https://github.com/USERNAME/REPOSITORY.git'
> To prevent you from losing history, non-fast-forward updates were rejected
> Merge the remote changes (e.g. 'git pull') before pushing again. See the
> 'Note about fast-forwards' section of 'git push --help' for details.
You can fix this by fetching and merging the changes made on the remote branch with the changes that you have made locally:
$ git fetch origin
# Fetches updates made to an online repository
$ git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work
Or, you can simply use git pull
to perform both commands at once:
$ git pull origin YOUR_BRANCH_NAME
# Grabs online updates and merges them with your local work
When collaborating with other developers using Git, you might encounter the error: failed to push some refs to [remote repo]
error.
This error mainly occurs when you attempt to push your local changes to GitHub while the local repository (repo) has not yet been updated with any changes made in the remote repo.
So Git is trying to tell you to update the local repo with the current changes in the remote before pushing your own changes. This is necessary so that you don’t override the changes made by others.
We’ll be discussing two possible ways of fixing this error in the sections that follow.
We can fix the error: failed to push some refs to [remote repo]
error in Git using the git pull origin [branch]
or git pull --rebase origin [branch]
commands. In most cases, the latter fixes the error.
Let’s go over how you can use the commands above.
How to Fix error: failed to push some refs to
Error in Git Using git pull
To send a pull request means to «fetch» new changes made to the remote repo and merge them with the local repo.
Once the merging is done, you can then push your own code changes to GitHub.
In our case, we’re trying to get rid of the error: failed to push some refs to [remote repo]
error by sending a pull request.
Here’s how you can do that:
git pull origin main
If you’re working with a different branch, then you’d have to replace main
in the example above with the name of your branch.
Just keep in mind that there are chances of failure when using this command to sync your remote and local repos to get rid of the error. If the request succeeds, then go on and run the command below to push your own changes:
git push -u origin main
If the error persists, you’ll get an error that says: fatal: refusing to merge unrelated histories
. In that case, use the solution in the next section.
How to Fix error: failed to push some refs to
Error in Git Using git pull --rebase
The git pull --rebase
command is helpful in situations where your local branch is a commit behind the remote branch.
To fix the error, go on and run following commands:
git pull --rebase origin main
git push -u origin main
If the first command above runs successfully, you should get a response that says: Successfully rebased and updated refs/heads/main
.
The second command pushes your local repo’s current state to the remote branch.
Summary
In this article, we talked about the error: failed to push some refs to [remote repo]
error.
This error occurs when you attempt to push your local changes to the remote repo without updating your local repo with new changes made to the remote repo.
We discussed two commands that you can use to fix the error: the git pull origin [branch]
and git pull --rebase origin [branch]
commands.
I hope this helps you fix the error.
Happy coding!
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
What is ‘failed to push some refs to’ error
failed to push some refs to is a Git error that many developers frequently face. It occurs when a developer attempts to push committed code to an external git repository. The ability to push code stopped working suddenly, despite it working yesterday or the day before. It can be a source of frustration and annoyance for many.
failed to push some refs to errors are often caused when changes are not committed before pushing, issues with Git pre-push hook, incorrect branch name, or the local repository not being in sync with the Git repository. It occurs most of the time because multiple contributors are working on the same branch and the remote repository is further along than what you currently have on your local machine.
It is easy for git pushes to overlap when working in teams or for ref heads to be in different positions. This overlap can cause the repository to be out of sync, which is why the failed to push some refs to error are so frequent.
What causes ‘failed to push some refs to’ error
When multiple developers work on the same branch, it can cause a sequencing issue in Git. A commit gets rejected and causes a failed to push some refs to
error because the remote branch contains code that you do not have locally. What this means is that your local git repository is not compatible with the remote origin.
Here is an abstraction of what incompatibility looks like in Git:
A -- B -- C -- D (on the remote) A -- B -- E (on your local machine)
Based on the above, your local machine is missing commits C and D. Meanwhile, you are trying to slot in your commit – E – between B and C on the remote.
Before Git lets you proceed, you will need to integrate the remote changes into your local repository. This step will fix any incompatibility issues and ensure that your version is up to date with the remote.
How can you fix ‘failed to push some refs to’ errors
Here are the scenarios that may cause the failed to push some refs
error, and how to correct them:
1.Another developer pushed a commit to the same branch
The error in your terminal looks like this:
To [email protected]:sometest.git ! [rejected] your-branch -] your-branch (non-fast-forward)
When this occurs, the head sits at different positions on the same code timeline, and Git does not know how to handle it. This is because the origin
repository is ahead of where you currently are. To fix this issue, run git pull
on your local repository. This should allow you to push to origin again.
git pull origin [your-branch] git push origin [your-branch]
2. You got a ‘master (non-fast-forward)’ error with a ‘failed to push some refs to’ error
A git fast-forward
happens when the ref pointer gets moved forward in the commit history. However, if your code diverges before it reaches the latest commit, it can cause the non-fast-forward
issue and lead to a failed to push some refs to
error.
To solve this issue, you can pull with the --rebase
flag. --rebase
will let you move your intended files to commit over to the latest pull code.
Here is how to pull with --rebase
:
git pull --rebase origin [branch]
3. You got a ‘master (fetch first)’ error with a ‘failed to push some refs to’ error
When this occurs, someone has pushed to the branch before you. Git wants you to pull first before you can push your committed changes.
To prevent the loss of your work during the pull
, you can stash
your local changes.
The common suggested fix is to use --force
flag to push through the local changes. However, it is good practice to avoid using the --force
flag as it can cause inconsistency issues. Instead, use --rebase
to move the ref
heads and update your local repository without causing a divergence in the remote repository.
Using --force
to try and fix the failed to push some refs to
error will only result in more errors in the long run. This occurs because --force
uses a brute force method that puts your current code and its ref
head as the source of truth.
As a result, the changes in the remote can be overwritten by what you have pushed, removing any features or updates that other developers may have committed.
Only use --force
if you are comfortable with features not on your local being overwritten with what you’ve currently got. Use the --force
flag if you are confident that your local repository in its current state is correct.
How to prevent ‘failed to push some refs to’ errors
To prevent failed to push some refs to
errors in Git, it is good practice to avoid having multiple developers work on the same branch simultaneously. Instead, use feature branches that merge into a master branch or something equivalent.
If you get a failed to push some refs to
error, the main thing to do is git pull to bring your local repo up to date with the remote. Avoid employing the --force
flag when using git pull
and prevent other developers’ accidental overwrites of committed features.
Use the --rebase
flag instead to avoid other errors from occurring while fixing your original failed to push some refs to
error.
Kubernetes Troubleshooting with Komodor
We hope that the guide above helps you better understand the troubleshooting steps you need to fix the failed to push some refs to
error.
Keep in mind that this is just one of many Git errors that can pop up in your K8s logs and cause the system to fail. Due to the complex and distributed nature of k8s,
the search for the root cause of each such failure can be stressful, disorienting, and time-consuming.
This is why we created Komodor, which acts as a single source of truth (SSOT) to streamline and shorten your k8s troubleshooting processes. Among other features, it offers:
- Change intelligence: Every issue is a result of a change. Within seconds we can help you understand exactly who did what and when.
- In-depth visibility: A complete activity timeline, showing all code and config changes, deployments, alerts, code diffs, pod logs, etc. All within one pane of glass with easy drill-down options.
- Insights into service dependencies: An easy way to understand cross-service changes and visualize their ripple effects across your entire system.
- Seamless notifications: Direct integration with your existing communication channels (e.g., Slack) so you’ll have all the information you need, when you need it.
A quick guide to fix Git error: failed to push some refs to in 5 ways
1. Overview
In this tutorial, We’ll learn how to fix the git error failed to push some refs to in 5 ways.
Most of the time you get this error while pushing your change git remote repository.
This might be working a few days back but suddenly started showing a weird error message «failed to push some refs to».
You are stuck at this point and do not what to do now. And you might be thinking because of my new changes?
For this error, there are mainly two reasons.
a) Your branch is set to main and not master
b) Remote repo has new changes and you do not have those changes on your laptop or local branch
Now, you knew about the actual reasons to get this common error.
Let us jump into the fixes.
2. Fix 1 Heroku — Git error: failed to push some refs to
To solve this error, you need to check what is the default branch on your github.com.
Once you find the right branch then you need to switch to the correct branch using git push command.
If the default branch is main on remote but it is master on your branch then please run below git push command.
Otherwise, it could be master as below.
If some else have pushed the new changes before you push to the remote repo. In this case, you do not have the recent commits on your laptop local repo.
So, you need to first pull the changes from that branch and then push your new commits.
To fix this error, follow the below steps.
git pull origin <your-branch> git push origin <your-branch>
It is strongly recommended to pull always changes first before pushing your commits to remote origin.
4. Fix 3 — Git error: failed to push some refs to
Sometimes, fix 2 did not work if you have more commits that produce the conflicts. In this case, the normal git pull command won’t work properly.
The solution to this problem is git-rebase.
Git rebase is a process of moving and arranging the sequence of comments into the new base commit.
Follow the below commands. Here the branch can be modified based on your branch.
Branch name can be master or main or another branch name.
git pull -rebase origin <your-branch-name> git push origin <your-branch-name>
5. Fix 4 — Git error: failed to push some refs to
You can try force push also. But not sure this will work always. If there are no conflicts, this will work.
git push -f origin master
6. Fix 5 — Git error: failed to push some refs to
the last solution is below. That deregister the current local repo and re-register with the remote.
rm -rf .git git init git remote add origin https://github.com/JavaProgramTo/Kotlin-Demo.git git remote -v (to see the remote origin) git add -A(add all files) git commit -m 'Added my project' git pull --rebase origin master git push origin master
7. Conclusion
In this article, We’ve seen how to fix the git error — failed to push some refs to.
1. Overview
Working with Git is an essential part of any developer’s day-to-day work. However, in the beginning, it could be overwhelming, and error messages might not be obvious. One of the most common issues people receive when starting working with Git is the error with refspec:
error: src refspec master does not match any
error: failed to push some refs to 'https://github.com/profile/repository.git'
In this tutorial, we’ll learn the reasons for this issue and how to resolve and mitigate it.
2. The Description of a Problem
Many of us have seen the refspec error message at least once within the console. This error occurs on pushing to a remote repository. Let’s try to understand what this line exactly means:
error: src refspec master does not match any
Simply put, this error message tells us that we don’t have a branch we want to push, which is the main reason for this error.
3. Going Through the Steps
The refspec error might appear when we cloned an uninitialized repository and tried to push a local repository. This is how Git services explain setting up a local repository. Here are the steps from GitHub:
$ echo "# repository" >> README.md
$ git init
$ git add README.md
$ git commit -m "first commit"
$ git branch -M main
$ git remote add origin https://github.com/profile/repository.git
$ git push -u origin main
We’ll refer to these steps in the paragraphs below.
4. Pushing a Non-existent Branch
Let’s go step by step through the instruction GitHub provides us.
4.1. Initializing a Repository
The first line creates a README.md file:
$ echo "# repository" >> README.md
The following command will initialize a local Git repository:
$ git init
This command may issue the following message:
hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint:
hint: git config --global init.defaultBranch <name>
hint:
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint:
hint: git branch -m <name>
In 2020 GitHub changed the default name of the branch created in a new repository from “master” to “main.” The same changes have happened on GitLab. It’s still configurable on GitHub, GitLab, and Git.
4.2. The First Commit
The subsequent two commands create a commit in our local repository:
$ git add README.md
$ git commit -m "first commit"
4.3. Renaming a Branch
The interesting thing happens in the following line:
$ git branch -M main
This line is responsible for renaming our current local branch to “main.” This happens because of the reason explained in the hint message. This line will rename our default branch to match the default branch name on our remote repository.
The steps provided by GitHub will contain the default name configured on the platform. However, this remaining became one of the most common reasons behind the refspec error. Let’s see what will happen if we have a local repository that uses “master” as a default branch and a remote which uses “main.” We’ll skip the renaming step for this example and go straight to setting up our remote repository:
$ git remote add origin https://github.com/profile/repository.git
4.4. The Problem
We’ll start experiencing problems on this line:
$ git push -u origin main
Let’s review this line and consult the documentation to understand what’s happening. This line pushes the changes from a branch, in this case, “main,” to a remote repository we configured in the previous line.
That means that the local repository should contain the “main” branch. However, the default local branch name is set to “master,” and we didn’t create a new “main“ branch or rename the “master” branch. In this case, Git won’t be able to find the “main“ branch to push, and we’ll get this error message:
error: src refspec main does not match any
error: failed to push some refs to 'origin'
Now this message makes more sense. As mentioned previously, this error tells us we don’t have the “main” branch. There is a couple of ways to resolve this problem. The first one is to rename our current “master“ branch to “main”:
$ git branch -M main
After the rename operation, we can repeat the push command, which will work without problems. At the same time, we can change the name of the branch we want to push from “main“ to “master” or any name we use as a default in our local repository. The following command will create a “master” branch on the remote repository:
$ git push -u origin master
And lastly, if we want to stick to the “master” name in our local repository and the “main” in our remote repository, we can explicitly set the upstream branch with the following command:
$ git push -u origin master:main
The flag -u will also set the upstream connection between the local “master“ branch and the remote “main“ branch. It means that the next time we can use the command without explicitly identifying the upstream branch:
$ git push
5. Pushing an Empty Repository
Another cause for this problem is pushing an empty repository. However, the reason behind it will be the same – trying to push a branch that doesn’t exist. Let’s assume that we’ve created a new repository. The branches are appropriately named. We added a file but didn’t commit it:
$ echo "# another-test-repo" >> README.md
$ git init
$ git add README.md
$ git branch -M main
$ git remote add origin https://github.com/profile/repository.git
$ git push -u origin main
Although we’re on the “main“ branch, technically, it doesn’t exist. For a branch to be created under .git/refs/heads, it should contain at least one commit. Let’s ensure that the folder .git/refs/heads in our repo is empty at this point:
$ ls .git/refs/heads
This command should show us an empty folder. Thus, as in the previous example, we’re trying to push a branch that doesn’t exist. A single commit will fix the problem. It will create a branch and make it possible to push the changes:
$ git commit -m "first commit"
$ git push -u origin master
6. Conclusion
Creating and initializing a new local repository isn’t a challenging task. However, skipping steps or blindly following instructions may result in errors. These errors sometimes are not explicitly understandable, especially for new Git users.
In this article, we’ve learned how to deal with refspec errors and what is the reason behind them.
I can’t push my chnages file in master now, Maybe I messed up with configs or something.My git code like as given below.
git add .
git commit -m"my changes"
git push origin master
Answer
Option 1.
git pull --rebase origin main
git push origin main
With Git 2.6+ (Sept. 2015), after having done (once)
git config --global pull.rebase true
git config --global rebase.autoStash true
Option 2.
git reset --mixed origin/master
git add .
git commit -m "enter your commit message here"
git push origin master
Option 3.
Not commiting initial changes before pushing also causes the problem.
Create new project folder and do step by step like as given below.This will address your problems.
1.git init
2.git remote add origin https://gitlab.com/xxx/xxx
3.git add .
4.git commit -m "your commit message"
5.git pull --rebase origin master
6.git push origin master
Option 4.
The error message «Failed to push some refs to remote» usually indicates that there is a conflict between the local and remote versions of the repository. This happens when someone else has pushed changes to the remote repository that conflict with the local changes you are trying to push.
To resolve this issue, you will need to perform a git pull to retrieve the remote changes and merge them with your local changes. Here’s the general process:
- Make sure you are on the branch that you want to push your changes to.
- Run the command git pull to retrieve the latest changes from the remote repository. This will automatically merge any remote changes into your local branch.
- If there are any merge conflicts, you will need to resolve them manually by editing the conflicting files. Once you’ve resolved the conflicts, stage and commit the changes.
- Re-run git push
It’s important to note that git pull is actually a shorthand for two commands: git fetch followed by git merge. The git fetch command retrieves the latest changes from the remote repository but doesn’t merge them into your local branch.
The git merge command merges the remote changes into your local branch. If you prefer, you can run these commands separately.
It’s also worth noting that If you want to discard your local changes and replace them with the remote version, you can use the command git reset —hard origin/<branch_name>, this command will discard your local changes and reset your branch to the state of the remote branch. However, be careful when using this command as it will permanently delete any local changes that have not been pushed.
Option 5.
In addition to what I mentioned before, another common cause of this error is when you try to push to a non-fast-forward branch. A non-fast-forward branch is a branch that has commits that are not present in the remote branch.
You can resolve this issue by using the git push
command with the --force
or -f
option, this will override the remote branch with your local commits. However, it’s important to be careful when using the --force
option, as it can cause other people’s work to be overwritten.
Another way of resolving this is to use git pull --rebase
before git push
. This will replay your local commits on top of the remote commits and preserve the remote commits.
You can also use the command git merge --ff-only origin/<branch_name>
to ensure that only fast-forward merge will happen.
It’s important to always coordinate with your team members before doing any force push, to avoid causing conflicts and overwriting other people’s work.
Related information
Sundar Neupane
I like working on projects with a team that cares about creating beautiful and usable interfaces.
If findandsolve.com felt valuable to you, feel free to share it.
This post talks about how to fix a git error.
error: src refspec master does not match any
error: failed to push some refs to ‘url.git’.
Possible causes for this error for the below use cases
- Create and commit changes to the remote repository
- Push the existing repository from the command line
Here are the steps and commands for creating and cloning and committing the repository
- git init
- git add README.md
- git commit -m “Initial Changes”.
- git remote add origin https://github.com/intkiran/angular-mock-api-json.git
- git push -u origin master
error: src refspec master does not match any error: failed to push some refs to ‘url.git’
There are two use cases success
and error
flow.
Let’s see how we can reproduce these error
use cases.
These are the not correct way of adding commits and pushing changes but given an example use case how we can reproduce this error?
-
I have a local project created
angular-crud-mock-api
in theb:\githubwork
directory. -
Create an empty repository in github.com my repository url.
https://github.com/intkiran/angular-mock-api-json.git
- Now want to commit angular-curd-mock-api code changes into the Repository url
existing local application created `angular-crud-mock-api which is not synced with the GitHub repository. - Let’s see how to add these changes to the remote repository
:githubworkangular-crud-mock-api>git remote add origin https://github.com/intkiran/angular-mock-api-json.git
- Issue git push command and throws an error
B:githubworkangular-crud-mock-api>git push -u origin master
error: src refspec master does not match any
error: failed to push some refs to 'https://github.com/intkiran/angular-mock-api-json.git'
That means, we have to add the first files or directory before pushing changes.
- Add the files and directories using the below command
git add .
B:githubworkangular-crud-mock-api>git add .
warning: LF will be replaced by CRLF in angular-crud-mock-api/.browserslistrc.
The file will have its original line endings in your working directory.
It adds the changes to the local repository in git.
Now, Let’s try to push changes to the remote repository using the git push
command.
- Next, push changes using the
git push
command.
B:githubworkangular-crud-mock-api>git push -u origin master
error: src refspec master does not match any
error: failed to push some refs to 'https://github.com/intkiran/angular-mock-api-json.git'
This error throws an error and you need to use the commit command before pushing the Command.
- commit changes
Here are the committed changes to the local repository.
B:githubworkangular-crud-mock-api>git commit -m "Initial changes"
[master (root-commit) 96c6c0c] Initial changes
29 files changed, 30724 insertions(+)
How to add add,commit push Success Flow in Github
Let’s see how we can reproduce these success
use cases.
Here is a sequence of commands you need to run to avoid the error.
git remote add origin https://github.com/intkiran/angular-mock-api-json.git
git add .
git commit -m "Initial changes".
git push -u origin master
Here is the output of push changes
B:githubworkangular-crud-mock-api>git push -u origin master
Enumerating objects: 38, done.
Counting objects: 100% (38/38), done.
Delta compression using up to 4 threads
Compressing objects: 100% (34/34), done.
Writing objects: 100% (38/38), 260.09 KiB | 5.20 MiB/s, done.
Total 38 (delta 1), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (1/1), done.
To https://github.com/intkiran/angular-mock-api-json.git
* [new branch] master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.
fix git error:src refspec origin does not match any
You have to carefully check the below things to avoid this error, if you create new repo or push an existing repository,
-
You forgot to add the files before pushing changes to the master or branch
-
Missing or skipping the
git add .
orgit commit
command throws an error
Here are steps for adding the files or directories
- git commit message enclosed in
double quotes
instead ofsingle quotes
Valid
git commit -m "initial changes"
Invalid
git commit -m 'initial commit'
- Please check the branch name with the push command
Usually, we will push changes using the below command.
git push -U origin `branchame`
push command push changes from the local repo to the remote repository branchname
Please make sure that branchname
exists.
‘master ‘ is the default branch.
Here is a correct command
git push -U origin master
Possible reasons
- Branch name not found
- Branch name spelling mistake or case insensitive
How to create a new repo to avoid this error in Git
here is a list of commands to avoid this error
git init
git add .
git commit -m 'message'
git push -u origin master
Conclusion
In this tutorial, Learn how to fix the git error:src refspec origin does not match any while working with git repositories.
fatal: No such remote ‘origin’ |
|
fatal: No such remote ‘origin’
fatal: No such remote ‘origin’
Скорее всего Вы пытаетесь выполнить
$ git remote set-url origin https://github.com/name/project.git
Попробуйте сперва выполнить
$ git remote add origin https://github.com/name/project.git
2
To https://github.com/YourName/yourproject.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to ‘https://github.com/YourName/yourproject.git’
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: ‘git pull …’) before pushing again.
hint: See the ‘Note about fast-forwards’ in ‘git push —help’ for details.
Скорее всего Вы пытаетесь выполнить
git push origin master
в новом репозитории.
При этом, когда
Вы создавали удалённый репозиторий на github Вы отметили опцию initialize with readme file.
Таким образом на удалённом репозитории файл
README.md
есть, а на локальном нет. Git не
понимает как такое могло произойти и предполагает, что на удалённый репозиторий кто-то (возможно Вы)
добавил что-то неотслеженное локальным репозиторием.
Первым делом попробуйте
$ git pull origin master
$ git push origin master
Git скачает файл
README.md
с удалённого репозитория и затем можно будет спокойно пушить
Если сделать pull не получилось, например, возникла ошибка
From https://github.com/andreiolegovichru/heiheiru
* branch master -> FETCH_HEAD
fatal: refusing to merge unrelated histories
Попробуйте
$ git pull —allow-unrelated-histories origin master
$ git push origin master
ERROR: Permission to AndreiOlegovich/qa-demo-project.git denied to andreiolegovichru.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
Возможная причина — git не видит ваш ключ. Либо ваш ключ уже используется для другого удалённого
хранилища.
Решить можно удалив стандарный ключ id_rsa.pub создать новую пару и добавить на удалённое хранилище.
Если этот способ не подходит — нужно настроить config.