🐣

【Git】リモートとローカル接続時のエラー対処

2024/03/11に公開

Gitでリモートリポジトリとローカルリポジトリを接続する際、少し詰まった部分を次回の対処用に記録。

今回発生したつまづきポイント

  1. リモートのデフォルトブランチとローカルブランチの名称違いによりプッシュができない
  2. デフォルトブランチ以外で不要なリモートブランチの削除

リモートのデフォルトブランチとローカルブランチの名称違いによりプッシュができない

xxx@xxxxx-xxxxx MINGW64 ~/Documents/Git/Quiz-Game (master)
$ git push origin main
error: src refspec main does not match any
error: failed to push some refs to 'github.com:xxxxxxx//Quiz-Game.git'

SSH keyを作成後、ローカルファイルをプッシュしようとした時に発生したエラーです。
恐らく、リモートにデフォルトブランチとして存在するmainブランチと一致するブランチがローカルにありませんよ。ということでしょうか。
原因はローカルブランチとして唯一存在したmasterブランチの名称が異なることと解釈した為、

$ git branch -m main

上記コマンドでmasterからmainブランチへ名称変更することで解決。だがしかしプッシュ時に・・・

$ git push origin main
Enter passphrase for key '/c/Users/xxxx/.ssh/id_rsa':
To github.com:xxxxxxx/Quiz-Game.git
 ! [rejected]        main -> main (non-fast-forward)
error: failed to push some refs to 'github.com:xxxxxxx/Quiz-Game.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.

リモートにREADME.mdがあったことでローカルに更新遅れが出ているとのことで、

$ git fetch origin main

フェッチからの

$ git merge origin/main

マージで無事リモートとローカルの差分がない状態にすることができました。

デフォルトブランチ以外で不要なリモートブランチの削除

さて、上述の最初のエラー発生時にmasterブランチをプッシュしているため、使わないmasterブランチが残ってしまっていて気持ちが悪い。リモートブランチの削除対応をしました。

$ git push origin --delete master

簡単ですね。

以上が、今回発生したエラーや不手際(?)の処理備忘録でした。
初めての投稿ですので、読みづらかったら申し訳ございません。
先人たちの記事を拝見しながら精進していきます。
最後までお読みいただきありがとうございます。

Discussion