ましめも

技術系メモ

git pullやpushでリモートのブランチ名を指定するのが面倒

新しいブランチを作成し、originにpushし共有するとき。

git checkout -b newbranch #新しいブランチを作成し、ついでにcheckout
#... コードの修正など
git push origin newbranch #リモートに反映

問題点

pushしたあとpullすると(他の人が同じブランチで作業などしてその変更を取り込みたい時など)次のようなエラーが発生する*1

$ git pull
You asked me to pull without telling me which branch you
want to merge with, and 'branch.newbranch.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.

If you often merge with the same branch, you may want to
use something like the following in your configuration file:
    [branch "newbranch"]
    remote = <nickname>
    merge = <remote-ref>

    [remote "<nickname>"]
    url = <url>
    fetch = <refspec>

See git-config(1) for details.

原因

エラーにも書かれているとおり、ブランチとリモート先との対応が設定されていないため。gitconfigに設定を追加するか、"git pull origin newbranch"のように明示的にリモートブランチを指定すればよい。

しかし、どっちの方法もめんどくさい。わずかな作業だが、めんどくさい。

もっと簡単な方法が

実はpushするときに-uオプションをつければ勝手に設定が追加される*2

git push -u origin newbranch

まとめ

ブランチ作成後の初回pushの際は-uオプションをつけよう

*1:ついでにいうと、"git push"を実行したときも同様のエラーが発生する

*2:git 1.7.x以降のみ