しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

gitでremoteブランチに切り替えるコマンドを短縮する

悩み

下コマンドをremoteブランチに切り替えてたんですが長くて辛いので短縮方法を調査。

$ git checkout -b remote_branch -t origin/remote_branch

Branch remote_branch set up to track local branch master.
Switched to a new branch 'remote_branch'

解決策

このページURLによると下コマンドで良いらしい。
長らくの悩みが一瞬で解決。

$ git checkout remote_branch

Branch remote_branch set up to track local branch master.
Switched to a new branch 'remote_branch'

色々検証

せっかくなので色々試してみる

$ git checkout -t origin/remote_branch # これは行けた
Branch remote_branch set up to track local branch master.
Switched to a new branch 'remote_branch'

$ git checkout -t remote_branch # これはダメ、-bをつけろと言われる
fatal: Missing branch name; try -b

$ git checkout -t -b remote_branch # 言われた通りに-bをつけると動く
Branch remote_branch set up to track local branch master.
Switched to a new branch 'remote_branch'

$ git checkout -b remote_branch # -tを外すとremoteを追いかけてくれない
Switched to a new branch 'remote_branch'

$ git checkout -b origin/remote_branch # これはorigin/remote_branchってブランチが作られる
Switched to a new branch 'origin/remote_branch'

同じブランチが2つあるとどうなるか試してみる

$ git remote add test http://xxx.com/xxx.git # remoteを追加

$ git checkout remote_branch # やはりダメ
error: pathspec 'remote_branch' did not match any file(s) known to git.

$ git checkout origin/remote_branch # これなら行けた
Switched to a new branch 'origin/remote_branch'

まとめ

remoteのブランチを追いかけたければ通常チェックアウトからgit checkout remote_branchのように -b を外すだけで行けるようです。
Forkで複数remoteがある場合はgit checkout origin/remote_branchのようにremoteの指定が必要でした。
git checkout remote_branchは便利だけどうっかり-bつけちゃいそうで怖いですね。-tを省略しない方がミスしにくいかもしれない。