Git push u origin main ошибка

This is a multi-part answer because there are two separate issues here that are tangling together now. Here’s a summary of what we’ll cover:

  • main vs master
  • error: src refspec main does not match any
  • reconciling separate main and master branches

Each of these is in its own section.

main vs master

Git itself has no special branch names.1 You could use main, master, trunk, or any other name as the name of your first branch. Git has traditionally used the name master here, but there is a project to make this configurable, so that if you are French or Spanish you can use the name principal or première or primero, or if you prefer Maori, you can use matua or tuatahi. Currently, you can do this manually during or after a git init,2 but the project makes Git just do it automatically, without requiring a second step: If for any reason you want any other name by default, you can configure that.

Meanwhile, GitHub have already chosen to leap ahead and make their default initial branch name main instead of master. But this leaves your Git and GitHub’s Git out of sync, as it were. For more about GitHub’s changeover, see
Difference Between Main Branch and Master Branch in Github?


1There are some technical flaws in this kind of claim. As we know, technically correct is the best kind of correct, so let me add a few caveats in this footnote:

  • Merging auto-generates a message of the form merge branch X into Y when you are on branch Y and run git merge X. However, when you’re on master, Git traditionally generates only a message of the form merge branch X.

  • A new, empty repository created by git init has no commits and therefore has no branches (because a branch can only exist by having commits on it). However, you must be on some branch in this new empty repository. So Git stores some name in the symbolic ref named HEAD. This is the branch name that you’re on, even if that branch name does not exist (yet). For a long time, Git has had, hard-coded into it, some code to stick the branch name master in there. (This is, in effect, what GitHub changed.)

  • There are a bunch of other string literals reading master in the source and documentation as well; they’re being converted to use the configuration settings but this will all take time.

2If you have Git 2.28 or later, run git init --initial-branch=name, and/or set init.defaultBranch with git config in your system or global configuration. If you have an earlier version of Git installed, or have already run git init, simply use git branch -m to rename master to whatever name you like.


error: src refspec main does not match any

This error message from Git is quite cryptic to newbies, but is actually pretty simple. The problems are that it’s loaded with jargon (webster; wikipedia), and abbreviates «source» to «src».

Git is all about commits. When we clone a repository, we have our Git reach out to some other Git. That other Git looks up a repository, and that other repository is full of commits. We then have our Git create a new repository locally, transfer into it all of their commits, and turn all of their branch names into remote-tracking names. Then our Git creates, in this new repository, one branch name, based on one of their branch names. At least, that’s the normal process. (And, if you know what all these terms mean, good! If not, don’t worry too much about them right now. The point to remember here is that we get all their commits and none of their branches, and then we normally have our Git create one branch to match one of theirs.)

Since Git is all about commits, this process—of copying all their commits, but only copying one of their branch names to a name spelled the same in our own repository—is all we need. The fact that our Git renames all of their branch names—so that with the one exception, we don’t have any branches at all—isn’t normally very important. Our own Git deals with this later, automatically, if and when it’s necessary.

When we use git push, we are asking our Git program, which is reading our own Git repository, to connect to some other Git program—typically running on a server machine—that can then write to some other Git repository. We’d like our Git to send their Git some of our commits. In particular, we want to send them our new commits: the ones we just made. Those are, after all, where we put all our good new stuff. (Git is all about commits, so that’s the only place we can put anything.)

Once we’ve sent these commits, though, we need to their Git to set one of their branch names to remember our new commits. That’s because the way Git finds commits is to use branch names.3 The real names of each commit are big ugly hash ID numbers, which nobody wants to remember or look at; so we have Git remember these numbers using the branch names. That way, we only have to look at the branch names, and these names can be meaningful to us: trunk, or feature/tall, or tuatahi, or whatever.

By default and convention, the way we do this using git push is pretty simple:

git push origin main

for instance. The git push part is the command that means send commits and ask them to set a name. The origin part is what Git calls a remote: a short name that, mostly, holds a URL. The main part at the end, here, is our branch name. That’s the one our Git is using to find our commits. We’ll have our Git send our commits, then ask their Git to set their main too.

This last part—where we’ve put in main here—is what Git calls a refspec. Refspecs actually let us put in two names, separated by a colon, or a couple of other forms. We can, for instance, use HEAD:main as in Arka’s answer (although for technical reasons we might want to use HEAD:refs/heads/main in many cases). But in simple cases, we can just use one branch name: git push origin main. The simple branch name is a simple form of refspec.

For this to work, the source name must be the name of an existing branch in our own Git repository. This is where things are going wrong.

(See also Message ‘src refspec master does not match any’ when pushing commits in Git)


3Git can use any name, not just a branch name. For instance, a tag name works fine. But this answer is about branch names because the question is about branch names, and branch names are the most common ones to use here.


What if our Git created only master?

Suppose we’re using GitHub and we’ve asked GitHub to make a new repository for us. They run a form of git init that supplies, as the new repository’s initial branch name, the name main. They may or may not create one commit, too. Let’s say we do have them create this one commit. That one commit will hold README and/or LICENSE files, based on what we choose using the web interface. Creating that initial commit actually creates the branch name main.

If we now clone their repository, we’ll get their one commit, which will be under their branch name main. Our Git will rename their main to origin/main and then create one new branch name, main, to match theirs. So all will be good.

But, if we create our own empty Git repository, using git init ourselves, our Git may set us up so that our first commit will create the name master. We won’t have a main branch: we’ll have a master branch instead.

Or, if we don’t have GitHub create an initial commit, the GitHub repository will be totally empty. Because it has no commits, it has no branches: a branch name is only allowed to exist if it specifies some commit. So if we clone this empty repository, we’ll have no branches either, and our Git won’t know to use main: our Git may instead use master. We’re back in that same situation, where our Git think the first name to create should be master.

So, in these various situations, we make our first commit(s), and they all go on a branch named master. If we now run:

git push -u origin main

(with or without the -u; I won’t go into the details about the -u here) our Git looks around in our Git repository for a branch named main. There isn’t one! So our Git just gives us that:

error: src refspec main does not match any

error message.

To fix this, we can either git push origin master—which sends our commits and then asks GitHub to create a new branch in the GitHub repository, with that branch name being master—or rename our master to whatever name we wanted, and then use that name:

git branch -m master xyzzy
git push -u origin xyzzy

will make the (single) branch name that we both use be xyzzy. If you want main here, rename your master to main.

What if you’ve accidentally made both branches?

Suppose we used GitHub to create a new repository, with their new default branch name main, that includes one initial commit with the usual README and LICENSE files. Then, without thinking about it, we used git init on our own machine to create our own new repository, with its default branch name master, and we made a commit or two on our master.

If we now rename our master to main:

git branch -m master main

and then try to push:

git push -u origin main

we get a different error:

 ! [rejected]        main -> main (non-fast-forward)

The reason for this is simple enough: They have a commit, that they find using their name main, that we do not have. If they change their name main to find the last commit that we’re sending them, they’ll lose the initial commit they made, with the README and LICENSE files.

You have a bunch of options here:

  • You can ignore the initial commit they made. It’s just a boilerplate commit, after all. You can tell them to throw it away entirely. Use git push --force as outlined in any of many existing StackOverflow answers.

  • You can obtain their initial commit and rebase your commits on those commits. This can be slightly tricky, because your first commit is a root commit. If your first commit contains README and/or LICENSE files, you’ll get an add/add conflict here. In this case it’s probably simpler to just force-push.

  • You can obtain their initial commit and merge your commits. In a modern Git, this requires using the --allow-unrelated-histories option. As with the rebase method, if your commits contain README and/or LICENSE files, you’ll get add/add conflicts. The resulting repository will also have two root commits. None of these are serious problems, but they might prove slightly annoying.

To obtain their commit, simply run git fetch origin. That will get GitHub’s first commit, and use the name origin/main in your own Git repository to remember it. You can then:

git rebase origin/main

or:

git merge --allow-unrelated-histories origin/main

to achieve the rebase or merge. You can choose whether to rename your branch to main, if you have not already done so, at any time before or after doing all of this.

$ git push -u origin main после этой комманды выдает
error: src refspec main does not match any
error: failed to push some refs to ‘https://github.com/…’
при этом, если я сделаю $ git push -u origin master, то создается новая ветка и туда отправляются нужные файлы, правда как с ней взаимодействовать — непонятно, все выводится списком
при этом я пытаюсь принять пуш, но ничего не происходит
62dc2baeeea93215697135.png

а еще если попытаться опять что-нибудь закоммитить $ git commit -m «#1»
то получается:
On branch master
nothing to commit, working tree clean
то есть локально у меня главная ветка master? а на гите main, из-за этого не может быть проблем?


  • Вопрос задан

    23 июл. 2022

  • 3975 просмотров

Команда git push -u origin main делает отправку локальной ветки main во внешний репозиторий origin, но ветки main не существует, о чем вам и сообщили в ошибке.

Вам нужно либо переименовать master в main:
git branch -M main

Либо так и написать, что вы хотите master отправить во внешний main
git push -u origin master:main

Но судя по скрину, у вас репозиторий не пустой. Вы уже создали там ветку с первоначальным коммитом. Поэтому вы не сможете просто так туда сделать push, так как ваши ветки не имеют общей истории. Это РАЗНЫЕ деревья. В таких случаях можно просо пересадить локальную ветку на вершину внешней через rebase. Либо создать ПУСТОЙ репо, как вы и сделали.

Пригласить эксперта

*** нет цензурных слов)
в моем репозитории на гите лежал файл readme.md
даже если я его пулил на локальный репозиторий, это не помогало
в итоге создал все заново без всяких доп файлов и нормально запушилось
+ добавил git branch -M main


  • Показать ещё
    Загружается…

09 июн. 2023, в 01:21

10000 руб./за проект

09 июн. 2023, в 01:06

50000 руб./за проект

09 июн. 2023, в 00:36

1000 руб./за проект

Минуточку внимания

Error: failed to push some refs to – How to Fix in Git

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

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

git error: failed to push some refs to remote repo

The git “error: failed to push some refs to remote repo” occurs when you try to push your local committed code to a remote repo with git push or git push -u origin main. The reason may be based on many issues related to the connection between the local branch and the remote branch and I will tell you a few. Before you can push to any remote GitHub repo, you have to make sure that there’s a connection between the remote and the local repo. It will be time saving if you do set an upstream for every branch so that you will just pull and push as you make changes to your code.

If you don’t have the required permissions, you will also not be able to push your source-code to a remote repo. This may due to the fact that you don’t own or you’re not part of the repo team/contributors. If that’s the case then what you need to do is to raise a pull request if you have already forked the repository. But if you do own the repo then it could mean that you have wrong configuration setup on your local environment.

If you’re presented with the bug failed to push some refs to remote error while pushing code to git, it could be that you did not commit your changes before pushing. Errors such as incorrect branch name, error: src refspec main does not match any and pre-receive hook declined are all related to the fact that your local repository not being in sync with the remote repo.

Also, when the remote origin is ahead of your local repo on your machine, you will not be able to push some refs to the remote repo. This may due to the fact that many contributors/team members working on the same branch. If other contributors push their changes, you have to pull and merge first before you can push so that your source code will match that of your team members. This implementation from the Git team is not really a bug but a hint to notify you that the remote origin has some file changes you do not have and it helps to avoid overlapping (meaning your local rep needs to be updated first so that you don’t override changes made by other team members.)

Below is how the error is presented…

$ git push origin main
Username for 'https://github.com': user_test
Password for 'https://github.com@github.com':
To https://github.com/justice1891/testpullpush.git
 ![rejected] main -> main (non-fast-forward)
error: failed to push some refs to 'https://github.com/ justice1891/testpullpush.git'

How to Fix the error: failed to push some refs to Error in Git. There are several ways you can fix the above error, but let take it step-by-step.

You can use the git command git pull origin [branch] or git pull --rebase origin [branch] to fix the error: failed to push some refs to [remote repo] error. After executing the above command, the error will be resolved and you should be able to push. Let me show you how to use the command.

What the command will do is that, it will send a pull request to the remote repo and fetch the new changes and merge it with your local repo. That’s how git ensures that both the local branch and the remote origin matches, and that means you can push your changes to GitHub after merging is done successfully. In our case, we have an error so let try to send a pull request first (you can do this on your terminal if you have Git already configured, or move to your local repo directory and use Git-Bash instead)

git pull origin main

Note that in the above code, we’re sending a pull request to fetch the changes from the main branch. If you have a different branch name like master, then replace main with that branch name. If the request didn’t succeed when you execute the above command whiles syncing your local and remote repo, make sure you have git properly configured on your system or check and see if there is a connection between the repos. Then you can go ahead and push your changes using below command:

git push -u origin main 

You should be able to push your code to the remote repo without encountering any bug. But if the error persists seek of other reasons and you’re presented with an error saying ‘fatal: refusing to merge unrelated histories’ then apply below solution to get it fixed.

How to fix the error “error: failed to push some refs” in Git Using git pull –rebase? If you have different number of commits in your local-branch it will be behind the remote branch and the first solution will not work for this situation. You can proceed and fix the error using the git pull –rebase command.

git pull --rebase origin main
git push -u origin main 

If you’re presented with the response Successfully rebased and updated refs/heads/main on the terminal after running the first command above, then the pull is successful. Both the local and the remote repo will be sync and rebase to have the same state and code or file changes with your local branch having one commit ahead the remote origin. That means you have to run the second command above to push your local commit, and this will push it state to the remote repo.

The next solution is to rename your branch and push again if you’re able to pull but cannot push to a remote repo. Sometimes because of other related reasons, git suggest that you rename your branch before you push, if your branch name contains hyphens and other special characters. Example, if your local branch name includes hyphens, replace it with underscore with git branch -m new_branch_name before you push.

git branch -m new_branch_name
git push -u new_branch_name

Check also, how to fix error – JSX expressions must have one parent element in React

Another reason that leads to the occurrence of the above error is when you add new changes with the command git add --all and you decide to push with git push without committing the changes. Git treat every commit as a separate version of your code or files in a branch so that you can switch back and forward and modify that commit separately. Make sure to commit all your code changes before you push, if not you will be presented with message saying “Everything up-to-date” meanwhile the actual files you just added needs to be pushed to the remote origin. Below is an example of such bug and how to solve it…

 git add –all
 git push

git everything up-to-date

You can see it says ‘Everything up-to-date’ meanwhile I was trying to push the changes I just added to the branch. If I run git status it will then list all the file changes, I just added waiting to be committed.

error failed to push some refs to

The point here is that, git will not push the changes you just added to the remote origin unless you commit first.

git add –-all 
git commit -m “first commit”
git push

Check also, How to fix typeError: ‘builtin_function_or_method’ object is not subscriptable in python

Summary

You have seen why the git error: failed to push some refs to [remote repo] occurs and how to resolve it with commands like git pull --rebase origin [branch], git pull origin [branch] and git push -u origin main. Please note carefully the underline reasons for the occurrence of the above error. It mainly because, you have to pull some changes from GitHub to your local repository before you can push. The error will be thrown if you don’t pull first and you attempt to push (git will not allow you to do that.)

Let me know if you did encounter any difficulties whiles applying any of the above solutions.

Keep coding!

Tagged error: failed to push some refs to

Понравилась статья? Поделить с друзьями:
  • Gilgen автоматические двери коды ошибок e2000
  • Gilgen автоматические двери коды ошибок 105
  • Gilgen door systems ошибка e105
  • Gilgen door systems ошибка 2000
  • Gilev ошибка при вызове конструктора