Error src refspec main does not match any ошибка

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.

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 newmain branch or rename the “master” branch. In this case, Git won’t be able to find themain 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 currentmaster 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 frommain 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 localmaster 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 themain 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.

$ 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, в 00:36

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

09 июн. 2023, в 00:26

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

09 июн. 2023, в 00:03

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

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

When you first try and push to a git repository, you may get the following error message:

error: src refspec master does not match any.
error: failed to push some refs to '[email protected] ... .git'

This is because you have not committed your files!

git commit -m "initial commit"
git push origin main

The above code will commit your files that are staged, before pushing them to your desired branch.

By default, we push our code to the main branch above. Swap this out with another branch if you need.

How to Show all References in Git

If you want to first see the references in git, then you can use the show-ref command:

git show-ref

# abc123d5d8d40586df855302eca139ee2b75f789 refs/heads/main
# abc123d5d8d40586df855302eca139ee2b75f789 refs/remotes/origin/main

Once you know this, you can push the code accordingly:

git push origin HEAD:<branch>

You may also ask these questions

How do I fix error SRC Refspec master does not match any?

First check what git references:

git show-ref

How do I fix error SRC Refspec main does not match any error failed to push some refs to?

git commit -m "<your message>"
git push origin main

How do I push to main branch GitHub?

git push -u origin main

How do I force git to push?

git push -u origin <branch> -f

1. Introduction

In this example, we shall explain to you in detail what an “error: src refspec main does not match any” in “git” is and how you can deal with such errors if you encounter them in the future.

2. Error Description

This error occurs when you try to push code from a local repository to a remote repository while using the "git push origin main" command in git command line using git bash and it happens that there is no main branch present hence an error.

3. Recreating the Error

There are several things that can trigger an "src refspec error main does not match any" error. The illustration below will show you how to produce this error.

Let’s assume you cloned a new repository where the default branch is master and there is no main branch. When you type the command: "git push origin main", it displays the "refspec main" error like this:

Fig. 1. git terminal displaying the "error: src refspec main does not match any"
Absence of the main branch triggering the “error: src refspec main does not match any”

4. Dealing with refspec errors

Now that you are aware of the "refspec error", let’s explain how to deal with such errors in git. Whenever you encounter such errors don’t panic just follow these procedures like this:

Display the remote branches connected to your local branch on your computer using the "git branch -b" command like this:

git branch -b

#results

# origin/master

From the above result, it is seen that we have only the master branch available in our remote repository and no main branch hence that explains why we had the "src refspec main does not match any" error.

In order for us to create a branch called main where we are going to migrate eventually to, we can either create branch directly on the Github website or we use the git terminal and type the command like this:

Fig. 2. Using the command "git checkout -b main" to create the main branch
Creating our main branch

After creating the "main branch" we are going to type the command "git push origin main" and it won’t display an error anymore proving that we have resolved the error.

5. Conclusion

When next you encounter an "error: src refspec main does not match any", just know that the main branch does not exist in your remote repository and hence try to create one.

Photo of Amanye Sirri

Sirri holds an Engineering Diploma in Computer Science with a major in Software Engineering from the African Institute of Computer Science in Cameroon. During her studies, she has been involved with a large number of projects ranging from programming to software engineering and design and analysis. She works as a computer teacher where she teaches students how to code in Java.


Back to top button

Понравилась статья? Поделить с друзьями:
  • Error report как исправить эту ошибку
  • Error reading from rom ошибка atiwinflash
  • Error reading data 12175 произошла ошибка безопасности faceit
  • Error program make not found in path eclipse ошибка
  • Error power off f24b ошибка на kyocera