gitでリモートにpushするとerror: failed to push some refs toが表示される

環境

  • macOS 10.14.6
  • git 2.23.0

事象

ローカルブランチにfeature/#7_testを作成し、コミット後にリモートへpushした際に以下エラーが発生

$ git push origin feature/#7_test
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 4 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 335 bytes | 335.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0)
remote: Resolving deltas: 100% (1/1), completed with 1 local object.
To https://github.com/seiya2130/git_tutorial.git
 ! [remote rejected] feature/#7_test -> feature/#7_test (cannot lock ref 'refs/heads/feature/#7_test': 'refs/heads/feature' exists; cannot create 'refs/heads/feature/#7_test')
error: failed to push some refs to 'https://github.com/seiya2130/git_tutorial.git'

原因

  • リモート追跡ブランチにremotes/origin/featureが残っていたため

ブランチ名で/(スラッシュ)が使われている場合、スラッシュ内で同名の単語があるとpush出来ない。

git branch -aでブランチを確認すると、リモート追跡ブランチにremotes/origin/featureがあった。

$ git branch -a
* feature/#7_test
  feature/test
  master
  remotes/origin/HEAD -> origin/master
  remotes/origin/feature
  remotes/origin/master
  remotes/origin/test

今回作成したブランチであるfeature/#7_testfeatureの部分が一致してしまい、pushが出来なかった

(同ディレクトリの中に同名フォルダが作れないようなイメージ)

対応

  • 不要なリモート追跡ブランチを削除し、pushする
    1. git remote prune orignでリモートブランチを削除する
    2. git push origin feature/#7_testで再度pushする

参考