Git push u origin main ошибка

whenever I'm trying to upload my files using git push -u origin main I'm getting error which is as follows error: src refspec main does not match any error: failed to push some refs to 'github.com:...

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

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

Команда 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, в 22:06

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

09 февр. 2023, в 22:01

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

09 февр. 2023, в 22:00

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

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

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

Анастасия Молодцова

Добрый день!

Подскажите, для push в команде git remote add origin надо указывать «git@github.com:repos/git-user/hexlet-git.git» ?
Команда git remote проходит, а при введении git push -u origin main выдаётся ошибка:
/usr/src/app/code-user$ git push -u origin main
ssh: Could not resolve hostname github.com: Temporary failure in name resolution
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.


14


0

Вячеслав Павлов

user-969b9f5e99b57fc9, здравствуйте.

git remote add origin git@github.com:<ИМЯ НА ГИТХАБЕ>/hexlet-git.git —
позволяет связать данный локальный репозиторий с удалённым (git@github.com:<ИМЯ НА ГИТХАБЕ>/hexlet-git.git), причем назначить этот удалённый репозиторий основным (origin). После выполнения команды можно использовать origin вместо того, чтобы вводить весь URL.

git push -u origin main — устанавливаете связь между той веткой, в которой вы находитесь и веткой main на удалённом сервере. Команду требуется выполнить единожды, чтобы потом можно было отправлять/принимать изменения лишь выполняя git push из ветки без указания всяких алиасов для сервера и удалённых веток. Это сделано для удобства.


0

Анастасия Молодцова

В ответ на команду git push -u origin main мне прилетает
ssh: Could not resolve hostname github.com: Temporary failure in name resolution
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

https://ibb.co/Dtxq67W


0

Вячеслав Павлов

Это команды для работы с репозиторием Github со своего компьютера. Вы же пытаетесь выполнить команды в онлайн среде, которая подготовлена для выполнения практики конкретного урока, что не верно.


0

Анастасия Молодцова

Тогда почему не срабатывает просто git push?
fatal: No configured push destination.
Either specify the URL from the command-line or configure a remote repository using

git remote add <name> <url>

and then push using the remote name

Также не срабатывает и git push -u origin main
error: src refspec main does not match any
error: failed to push some refs to ‘origin’

git push <name>


0

Maksim Litvinov

Добрый день! Напишите, пожалуйста, пошагово, какие команды и где вы выполняете. Вячеслав правильно ответил. Команда git remote add origin git@github.com:<ИМЯ НА ГИТХАБЕ>/hexlet-git.git добавляет новый удаленный репозиторий для текущего локального. Команда git push -u origin main устанавливает отслеживание ветки. После этого можно просто писать git push без указания имени репозитория и ветки.


0

Анастасия Молодцова

Выше я выкладывала скриншот одной из попыток
https://ibb.co/Dtxq67W


0

Maksim Litvinov

Обратите внимание на адрес репозитория: git@github.com:repos/git-user/hexlet-git.git. Он точно правильный? Адрес репозитория выглядит примерно так: git@github.com:<ИМЯ НА ГИТХАБЕ>/hexlet-git.git. То есть, если имя пользователя на гитхабе user, адрес будет выглядеть так: git@github.com:user/hexlet-git.git


0

Анастасия Молодцова

Простите, я не понимаю, какое мне имя пользователя на github указать
code-user и user не подходят


0

Maksim Litvinov

Да, они не подходят. Я привел это имя только для примера. Вместо него вы должны указать то имя, под которым вы зарегестрировались на github. Подскажите, вы регистрировались на github?


0

Анастасия Молодцова

Да, есть
Я так пробовала в предыдущем задании (про интеграции с GIT)
Попробовала и здесь
При указании моего имени на github выдаёт ошибку:
ssh: Could not resolve hostname github.com: Temporary failure in name resolution
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
Кроме того, при решении похожей задачи к блоку про интеграцию, не надо было вводить git remote, а просто git push
Видимо, мне надо завязывать с программированием прямо сейчас или искать другие курсы. Вас я не понимаю


0

Maksim Litvinov

Напишите, пожалуйста, какой url вы указывали, когда указывали свое имя на гитхаб


0


0

Анастасия Молодцова

Только я теперь не понимаю, почему там не появились файлы, которые были в задании в интеграции. Там у меня тоже были проблемы с пушем. В итоге сработал просто код git push
А получается, что файлы в github не выложились
Может быть можно как-то slack пообщаться с вами?


0

Maksim Litvinov

Отлично, теперь адрес репозитория верный. Теперь давайте проверим, этот ли репозиторий установлен в качестве удаленного. Выполните команду git romote -v и скопируйте сюда её вывод. Эта команда выведет удаленные репозитории, добавленные для текущего локального.

Будет лучше, если все обсуждения, касающиеся урока, будут находится в этом уроке. Так другие студенты, у которых возник аналогичный вопрос, смогут прочитать их.


0

I’m trying to push one of my projects to github, and I keep getting this error:

peeplesoft@jane3:~/846156 (master) $ git push

fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

     git push --set-upstream origin master

So I tried it and got this:

peeplesoft@jane3:~/846156 (master) $ git push --set-upstream origin master

fatal: Authentication failed

Another stackoverflow thread suggested I try the following, with disappointing results.

peeplesoft@jane3:~/846156 (master) $ git push -u origin master

fatal: Authentication failed

Then I tried this:

peeplesoft@jane3:~/846156 (master) $ git config remote.origin.push HEAD

peeplesoft@jane3:~/846156 (master) $ git push

fatal: Authentication failed

Any hints?

alex's user avatar

alex

473k199 gold badges872 silver badges978 bronze badges

asked May 1, 2014 at 3:38

user1524361's user avatar

7

You fixed the push, but, independently of that push issue (which I explained in «Why do I need to explicitly push a new branch?»: git push -u origin master or git push -u origin --all), you need now to resolve the authentication issue.

That depends on your url (ssh as in ‘git@github.com/yourRepo, or https as in https://github.com/You/YourRepo)

For https url:

If your account is protected by the two-factor authentication, your regular password won’t work (for https url), as explained here or here.

Same problem if your password contains special character (as in this answer)

If https doesn’t work (because you don’t want to generate a secondary key, a PAT: personal Access Token), then you can switch to ssh, as I have shown here.


As noted by qwerty in the comments, you can automatically create the branch of same name on the remote with:

git push -u origin head 

Why?

  • HEAD (see your .gitHEAD file) has the refspec of the currently checked out branch (for example: ref: refs/heads/master)
  • the default push policy is simple

Since the refpec used for this push is head: (no destination), a missing :<dst> means to update the same ref as the <src> (head, which is a branch).

That won’t work if HEAD is detached though.


Or you can use Git 2.37 (Q3 2022) and the new global option push.autoSetupRemote:

git config --global push.autoSetupRemote true
git push

answered May 1, 2014 at 4:42

VonC's user avatar

VonCVonC

1.2m508 gold badges4248 silver badges5069 bronze badges

4

Also you can use the following command:

git push -u origin master

This creates (-u) another branch in your remote repo. Once the authentication using ssh is done that is.

answered Jul 19, 2014 at 0:40

TantrajJa's user avatar

TantrajJaTantrajJa

1,9672 gold badges14 silver badges9 bronze badges

2

If you define the action git push it should take it if no refspec is given on the command line, no refspec is configured in the remote, and no refspec is implied by any of the options given on the command line.

Just do it:

git config --global push.default current

then

git push

answered Sep 11, 2019 at 16:25

DariusV's user avatar

DariusVDariusV

2,54314 silver badges21 bronze badges

3

Apparently you also get this error message when you forget the --all parameter when pushing for the first time. I wrote

git push -u origin

which gave this error, it should have been

git push -u origin --all

Oh how I love these copy-paste errors …

answered Nov 27, 2014 at 8:55

TheEye's user avatar

TheEyeTheEye

9,1902 gold badges41 silver badges58 bronze badges

1

Please try this scenario

git push -f --set-upstream origin master

Ajmal Sha's user avatar

Ajmal Sha

8664 gold badges17 silver badges36 bronze badges

answered May 2, 2018 at 12:10

hoochanlon's user avatar

hoochanlonhoochanlon

2612 silver badges5 bronze badges

5

use this command first before you push in to the branch

git config --global push.default current

After executing the above command use git push command.

Paul Roub's user avatar

Paul Roub

36.2k27 gold badges82 silver badges90 bronze badges

answered Apr 19, 2021 at 13:50

KileMax's user avatar

KileMaxKileMax

1931 silver badge7 bronze badges

1

You need to configure the remote first, then push.

git remote add origin url-to-your-repo

Actual Instructions

answered Mar 30, 2017 at 7:51

Santosh Pillai's user avatar

Santosh PillaiSantosh Pillai

7,8591 gold badge30 silver badges26 bronze badges

It means that you don’t have your branch(the branch that you want to push) in your remote repository, in other words it does not exist in your remote repository(it wasn’t created yet)…
So use this Code:

git push -u origin 'your branch name'

this code will create your branch in your remote repository and will push it…

Enos Okello's user avatar

answered Apr 13, 2021 at 11:30

jamal zare's user avatar

jamal zarejamal zare

95911 silver badges12 bronze badges

1

on a very simple side, once you have other branches, you can’t just use for pushing a branch

git push

But you need to specify the branch now, even if you have checkout the branch you want to push, so

git push origin <feature_branch>

Where can be even the master branch

answered Nov 15, 2018 at 9:16

Abhishek's user avatar

AbhishekAbhishek

3,2874 gold badges31 silver badges51 bronze badges

Well, I was having the same trouble while uploading and I resolved it by
doing the same thing which it says to do:
Earlier I was trying to push through terminal to my repository in linux by https
like

git push https://github.com/SiddharthChoudhary/ClientServerCloudComputing.git

But was not getting any result and hence I went down deeper and tried:

git push --set-upstream https://github.com/SiddharthChoudhary/ClientServerCloudComputing.git master

And it worked. Thus then you will get prompted with username and password.
I also generated a token and instead of Password I pasted the token and thus, being done successfully.

  1. To generate a token go to your Github account and in Developer Settings and then create another token.
  2. After getting that, copy
    that token and paste in the password prompt when it’s been asked.

zar's user avatar

zar

10.9k13 gold badges91 silver badges171 bronze badges

answered Oct 16, 2018 at 16:47

Siddharth Choudhary's user avatar

2

I made the simple error of forgetting to commit:

git commit -m "first commit"

then git push origin master worked.

answered Jul 13, 2018 at 23:44

yl_low's user avatar

yl_lowyl_low

1,0892 gold badges17 silver badges25 bronze badges

I had the same problem

enter image description here

I resolved it that used below command

$ git branch --set-upstream develop origin/develop

and it will add a config in the config file in the .git folder.

enter image description here

answered Jan 7, 2019 at 2:33

bluetata's user avatar

bluetatabluetata

5296 silver badges12 bronze badges

1

First use git pull origin your_branch_name
Then use git push origin your_branch_name

answered Feb 16, 2017 at 3:20

FRabbi's user avatar

FRabbiFRabbi

1351 silver badge6 bronze badges

2

There is a simple solution to this which worked for me on macOS Sierra.
I did these two commands:

git pull --rebase git_url(Ex: https://github.com/username/reponame.git)
git push origin master

If it shows any fatal error regarding upstream after any future push then simply run :

git push --set-upstream origin master

answered Sep 10, 2017 at 12:18

theRana's user avatar

theRanatheRana

6949 silver badges10 bronze badges

If you constantly get the following git error message after attempting a git push with a new local branch:

fatal: The current branch has no upstream branch.

To push the current branch and set the remote as upstream, use

git push --set-upstream origin <branchname>

Then the issue is that you have not configured git to always create new branches on the remote from local ones.

The permanent fix if you always want to just create that new branch on the remote to mirror and track your local branch is:

git config --global push.default current

Now you can git push without any errors!

https://vancelucas.com/blog/how-to-fix-git-fatal-the-current-branch-has-no-upstream-branch/

fcdt's user avatar

fcdt

2,3315 gold badges12 silver badges26 bronze badges

answered Oct 19, 2020 at 23:07

Angie Cristina's user avatar

For me, it was because I had deleted the hidden .git folder.

I fixed it by deleting the folder, re-cloning, and re-making the changes.

answered Sep 10, 2019 at 2:18

AmmarBaali's user avatar

I was getting this error because I was trying to push the code without write access, I only had read access.

In Bitbucket, you can check access on the right side when you open your repo (Repository details) :

answered Sep 21, 2022 at 6:53

stackich's user avatar

stackichstackich

2,8993 gold badges14 silver badges31 bronze badges

1. A computer and your github associated. Use SSH. Computer code so you do not need to submit verified enter image description here

2. git can not manage empty folder. So you have to write such a readme.md saved in a file. Otherwise you will not find the file.

3. Your local project is nothing new projects move over. Please

git init

git remote add origin +"githublink"

git add .

git commit -m "" go again.

4. then git pull origin master (the key)

5. At last git push origin master (solve all problem).

http://my.oschina.net/psuyun/blog/123005 参考链接

N.Droid's user avatar

N.Droid

2,04316 silver badges28 bronze badges

answered Jul 15, 2016 at 13:30

王逍遥's user avatar

If you are trying to push your code direct to the master branch then use command

git push origin master

It helps me.

answered Apr 26, 2018 at 6:02

HitechZa's user avatar

I also got the same error.I think it was because I clone it and try to push back.
$ git push -u origin master
This is the right command.Try that

Counting objects: 8, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (8/8), 691 bytes | 46.00 KiB/s, done.
Total 8 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), done.

  • [new branch] master -> master
    Branch master set up to track remote branch master from origin.

    It was successful. Try to create new u branch 
    

answered May 11, 2018 at 16:08

Malsha's user avatar

I had the same problem, the cause was that I forgot to specify the branch

git push myorigin feature/23082018_my-feature_eb

answered Aug 23, 2018 at 9:25

Black's user avatar

BlackBlack

17k36 gold badges150 silver badges256 bronze badges

For me, I was pushing the changes to a private repo to which I didn’t had the write access.
Make sure you have the valid access rights while performing push or pull operations.

You can directly verify via

answered Jul 26, 2019 at 8:14

mayank dhawariya's user avatar

1

If you are on any branch, you can use this:

git push origin head -u

This will automatically create new branch of the same name on the remote.

answered May 15, 2020 at 10:17

Qwerty's user avatar

QwertyQwerty

27.3k21 gold badges107 silver badges129 bronze badges

commit your code using

git commit -m "first commit"

then config your mail id using

git config user.email "example@example.com"

this is work for me

Boken's user avatar

Boken

4,5259 gold badges33 silver badges42 bronze badges

answered Jul 14, 2020 at 8:11

Bala visakh's user avatar

The thing that helped me:
I saw that the connection between my directory to git wasn’t established —
so I did again:
git push -u origin main

ghilesZ's user avatar

ghilesZ

1,4051 gold badge17 silver badges30 bronze badges

answered Jan 28, 2021 at 12:12

mi re la's user avatar

Different case with same error (backing up to external drive), the issue was that I’d set up the remote repo with clone. Works every time if you set the remote repo up with bare initially

cd F:/backups/dir
git init --bare
cd C:/working/dir
git remote add backup F:/backups/dir
git push backup master

answered Feb 1, 2021 at 0:29

Dave's user avatar

DaveDave

1,3592 gold badges16 silver badges14 bronze badges

In my mind, this is just a wrong default git behavior.
Having reviewed all options support by git, also reviewed the relevant git code:

https://github.com/git/git/blob/140045821aa78da3a80a7d7c8f707b955e1ab40d/builtin/push.c#L188

The best solution I would suggest it simply override the push default command:

git config --global alias.pu 'push -u'

This basically changes the default behavior of push so that makes sense.

answered Mar 8, 2021 at 7:23

JAR.JAR.beans's user avatar

JAR.JAR.beansJAR.JAR.beans

9,3594 gold badges44 silver badges56 bronze badges

Encountered just about the same problem, but not from the master branch.
I tried to push two (2) branches to my remote repository, by using the $ git push command; which unfortunately threw up the:

fatal: The current branch <branch-name> has no upstream branch. To push the current branch and set the remote as upstream, use

 git push --set-upstream origin <branch-name>

I got it fixed with this command below:

$ git push -u origin --all

PS: The solution provided here should, i believe, make it easier for git to track out branches remotely; this could come in-handy someday, when working on projects with couple of branches.

answered Jul 25, 2021 at 22:14

Bravo Stack's user avatar

1

In my case, I have a local branch called Master, whereas master is on Github.
I simply rename my Master -> master and checkout to master.
And then push it. It works for me.

answered May 1, 2022 at 13:39

UC57's user avatar

UC57UC57

3594 silver badges16 bronze badges

It is better, Clone this repo newly. Maybe it just lost track.

answered Oct 31, 2022 at 5:16

Mujahidul Islam's user avatar

I’m trying to push one of my projects to github, and I keep getting this error:

peeplesoft@jane3:~/846156 (master) $ git push

fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

     git push --set-upstream origin master

So I tried it and got this:

peeplesoft@jane3:~/846156 (master) $ git push --set-upstream origin master

fatal: Authentication failed

Another stackoverflow thread suggested I try the following, with disappointing results.

peeplesoft@jane3:~/846156 (master) $ git push -u origin master

fatal: Authentication failed

Then I tried this:

peeplesoft@jane3:~/846156 (master) $ git config remote.origin.push HEAD

peeplesoft@jane3:~/846156 (master) $ git push

fatal: Authentication failed

Any hints?

alex's user avatar

alex

473k199 gold badges872 silver badges978 bronze badges

asked May 1, 2014 at 3:38

user1524361's user avatar

7

You fixed the push, but, independently of that push issue (which I explained in «Why do I need to explicitly push a new branch?»: git push -u origin master or git push -u origin --all), you need now to resolve the authentication issue.

That depends on your url (ssh as in ‘git@github.com/yourRepo, or https as in https://github.com/You/YourRepo)

For https url:

If your account is protected by the two-factor authentication, your regular password won’t work (for https url), as explained here or here.

Same problem if your password contains special character (as in this answer)

If https doesn’t work (because you don’t want to generate a secondary key, a PAT: personal Access Token), then you can switch to ssh, as I have shown here.


As noted by qwerty in the comments, you can automatically create the branch of same name on the remote with:

git push -u origin head 

Why?

  • HEAD (see your .gitHEAD file) has the refspec of the currently checked out branch (for example: ref: refs/heads/master)
  • the default push policy is simple

Since the refpec used for this push is head: (no destination), a missing :<dst> means to update the same ref as the <src> (head, which is a branch).

That won’t work if HEAD is detached though.


Or you can use Git 2.37 (Q3 2022) and the new global option push.autoSetupRemote:

git config --global push.autoSetupRemote true
git push

answered May 1, 2014 at 4:42

VonC's user avatar

VonCVonC

1.2m508 gold badges4248 silver badges5069 bronze badges

4

Also you can use the following command:

git push -u origin master

This creates (-u) another branch in your remote repo. Once the authentication using ssh is done that is.

answered Jul 19, 2014 at 0:40

TantrajJa's user avatar

TantrajJaTantrajJa

1,9672 gold badges14 silver badges9 bronze badges

2

If you define the action git push it should take it if no refspec is given on the command line, no refspec is configured in the remote, and no refspec is implied by any of the options given on the command line.

Just do it:

git config --global push.default current

then

git push

answered Sep 11, 2019 at 16:25

DariusV's user avatar

DariusVDariusV

2,54314 silver badges21 bronze badges

3

Apparently you also get this error message when you forget the --all parameter when pushing for the first time. I wrote

git push -u origin

which gave this error, it should have been

git push -u origin --all

Oh how I love these copy-paste errors …

answered Nov 27, 2014 at 8:55

TheEye's user avatar

TheEyeTheEye

9,1902 gold badges41 silver badges58 bronze badges

1

Please try this scenario

git push -f --set-upstream origin master

Ajmal Sha's user avatar

Ajmal Sha

8664 gold badges17 silver badges36 bronze badges

answered May 2, 2018 at 12:10

hoochanlon's user avatar

hoochanlonhoochanlon

2612 silver badges5 bronze badges

5

use this command first before you push in to the branch

git config --global push.default current

After executing the above command use git push command.

Paul Roub's user avatar

Paul Roub

36.2k27 gold badges82 silver badges90 bronze badges

answered Apr 19, 2021 at 13:50

KileMax's user avatar

KileMaxKileMax

1931 silver badge7 bronze badges

1

You need to configure the remote first, then push.

git remote add origin url-to-your-repo

Actual Instructions

answered Mar 30, 2017 at 7:51

Santosh Pillai's user avatar

Santosh PillaiSantosh Pillai

7,8591 gold badge30 silver badges26 bronze badges

It means that you don’t have your branch(the branch that you want to push) in your remote repository, in other words it does not exist in your remote repository(it wasn’t created yet)…
So use this Code:

git push -u origin 'your branch name'

this code will create your branch in your remote repository and will push it…

Enos Okello's user avatar

answered Apr 13, 2021 at 11:30

jamal zare's user avatar

jamal zarejamal zare

95911 silver badges12 bronze badges

1

on a very simple side, once you have other branches, you can’t just use for pushing a branch

git push

But you need to specify the branch now, even if you have checkout the branch you want to push, so

git push origin <feature_branch>

Where can be even the master branch

answered Nov 15, 2018 at 9:16

Abhishek's user avatar

AbhishekAbhishek

3,2874 gold badges31 silver badges51 bronze badges

Well, I was having the same trouble while uploading and I resolved it by
doing the same thing which it says to do:
Earlier I was trying to push through terminal to my repository in linux by https
like

git push https://github.com/SiddharthChoudhary/ClientServerCloudComputing.git

But was not getting any result and hence I went down deeper and tried:

git push --set-upstream https://github.com/SiddharthChoudhary/ClientServerCloudComputing.git master

And it worked. Thus then you will get prompted with username and password.
I also generated a token and instead of Password I pasted the token and thus, being done successfully.

  1. To generate a token go to your Github account and in Developer Settings and then create another token.
  2. After getting that, copy
    that token and paste in the password prompt when it’s been asked.

zar's user avatar

zar

10.9k13 gold badges91 silver badges171 bronze badges

answered Oct 16, 2018 at 16:47

Siddharth Choudhary's user avatar

2

I made the simple error of forgetting to commit:

git commit -m "first commit"

then git push origin master worked.

answered Jul 13, 2018 at 23:44

yl_low's user avatar

yl_lowyl_low

1,0892 gold badges17 silver badges25 bronze badges

I had the same problem

enter image description here

I resolved it that used below command

$ git branch --set-upstream develop origin/develop

and it will add a config in the config file in the .git folder.

enter image description here

answered Jan 7, 2019 at 2:33

bluetata's user avatar

bluetatabluetata

5296 silver badges12 bronze badges

1

First use git pull origin your_branch_name
Then use git push origin your_branch_name

answered Feb 16, 2017 at 3:20

FRabbi's user avatar

FRabbiFRabbi

1351 silver badge6 bronze badges

2

There is a simple solution to this which worked for me on macOS Sierra.
I did these two commands:

git pull --rebase git_url(Ex: https://github.com/username/reponame.git)
git push origin master

If it shows any fatal error regarding upstream after any future push then simply run :

git push --set-upstream origin master

answered Sep 10, 2017 at 12:18

theRana's user avatar

theRanatheRana

6949 silver badges10 bronze badges

If you constantly get the following git error message after attempting a git push with a new local branch:

fatal: The current branch has no upstream branch.

To push the current branch and set the remote as upstream, use

git push --set-upstream origin <branchname>

Then the issue is that you have not configured git to always create new branches on the remote from local ones.

The permanent fix if you always want to just create that new branch on the remote to mirror and track your local branch is:

git config --global push.default current

Now you can git push without any errors!

https://vancelucas.com/blog/how-to-fix-git-fatal-the-current-branch-has-no-upstream-branch/

fcdt's user avatar

fcdt

2,3315 gold badges12 silver badges26 bronze badges

answered Oct 19, 2020 at 23:07

Angie Cristina's user avatar

For me, it was because I had deleted the hidden .git folder.

I fixed it by deleting the folder, re-cloning, and re-making the changes.

answered Sep 10, 2019 at 2:18

AmmarBaali's user avatar

I was getting this error because I was trying to push the code without write access, I only had read access.

In Bitbucket, you can check access on the right side when you open your repo (Repository details) :

answered Sep 21, 2022 at 6:53

stackich's user avatar

stackichstackich

2,8993 gold badges14 silver badges31 bronze badges

1. A computer and your github associated. Use SSH. Computer code so you do not need to submit verified enter image description here

2. git can not manage empty folder. So you have to write such a readme.md saved in a file. Otherwise you will not find the file.

3. Your local project is nothing new projects move over. Please

git init

git remote add origin +"githublink"

git add .

git commit -m "" go again.

4. then git pull origin master (the key)

5. At last git push origin master (solve all problem).

http://my.oschina.net/psuyun/blog/123005 参考链接

N.Droid's user avatar

N.Droid

2,04316 silver badges28 bronze badges

answered Jul 15, 2016 at 13:30

王逍遥's user avatar

If you are trying to push your code direct to the master branch then use command

git push origin master

It helps me.

answered Apr 26, 2018 at 6:02

HitechZa's user avatar

I also got the same error.I think it was because I clone it and try to push back.
$ git push -u origin master
This is the right command.Try that

Counting objects: 8, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (8/8), 691 bytes | 46.00 KiB/s, done.
Total 8 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), done.

  • [new branch] master -> master
    Branch master set up to track remote branch master from origin.

    It was successful. Try to create new u branch 
    

answered May 11, 2018 at 16:08

Malsha's user avatar

I had the same problem, the cause was that I forgot to specify the branch

git push myorigin feature/23082018_my-feature_eb

answered Aug 23, 2018 at 9:25

Black's user avatar

BlackBlack

17k36 gold badges150 silver badges256 bronze badges

For me, I was pushing the changes to a private repo to which I didn’t had the write access.
Make sure you have the valid access rights while performing push or pull operations.

You can directly verify via

answered Jul 26, 2019 at 8:14

mayank dhawariya's user avatar

1

If you are on any branch, you can use this:

git push origin head -u

This will automatically create new branch of the same name on the remote.

answered May 15, 2020 at 10:17

Qwerty's user avatar

QwertyQwerty

27.3k21 gold badges107 silver badges129 bronze badges

commit your code using

git commit -m "first commit"

then config your mail id using

git config user.email "example@example.com"

this is work for me

Boken's user avatar

Boken

4,5259 gold badges33 silver badges42 bronze badges

answered Jul 14, 2020 at 8:11

Bala visakh's user avatar

The thing that helped me:
I saw that the connection between my directory to git wasn’t established —
so I did again:
git push -u origin main

ghilesZ's user avatar

ghilesZ

1,4051 gold badge17 silver badges30 bronze badges

answered Jan 28, 2021 at 12:12

mi re la's user avatar

Different case with same error (backing up to external drive), the issue was that I’d set up the remote repo with clone. Works every time if you set the remote repo up with bare initially

cd F:/backups/dir
git init --bare
cd C:/working/dir
git remote add backup F:/backups/dir
git push backup master

answered Feb 1, 2021 at 0:29

Dave's user avatar

DaveDave

1,3592 gold badges16 silver badges14 bronze badges

In my mind, this is just a wrong default git behavior.
Having reviewed all options support by git, also reviewed the relevant git code:

https://github.com/git/git/blob/140045821aa78da3a80a7d7c8f707b955e1ab40d/builtin/push.c#L188

The best solution I would suggest it simply override the push default command:

git config --global alias.pu 'push -u'

This basically changes the default behavior of push so that makes sense.

answered Mar 8, 2021 at 7:23

JAR.JAR.beans's user avatar

JAR.JAR.beansJAR.JAR.beans

9,3594 gold badges44 silver badges56 bronze badges

Encountered just about the same problem, but not from the master branch.
I tried to push two (2) branches to my remote repository, by using the $ git push command; which unfortunately threw up the:

fatal: The current branch <branch-name> has no upstream branch. To push the current branch and set the remote as upstream, use

 git push --set-upstream origin <branch-name>

I got it fixed with this command below:

$ git push -u origin --all

PS: The solution provided here should, i believe, make it easier for git to track out branches remotely; this could come in-handy someday, when working on projects with couple of branches.

answered Jul 25, 2021 at 22:14

Bravo Stack's user avatar

1

In my case, I have a local branch called Master, whereas master is on Github.
I simply rename my Master -> master and checkout to master.
And then push it. It works for me.

answered May 1, 2022 at 13:39

UC57's user avatar

UC57UC57

3594 silver badges16 bronze badges

It is better, Clone this repo newly. Maybe it just lost track.

answered Oct 31, 2022 at 5:16

Mujahidul Islam's user avatar




Содержание статьи


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.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Git push error code 22
  • Git pull error your local changes to the following files would be overwritten by merge
  • Git pull error cannot lock ref
  • Git public key error
  • Git needs merge error you need to resolve your current index first

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии