Skip to content

Instantly share code, notes, and snippets.

@hankei6km
Last active October 29, 2020 00:53
Show Gist options
  • Save hankei6km/8d76d333d606321aa42b94ccd792b8c9 to your computer and use it in GitHub Desktop.
Save hankei6km/8d76d333d606321aa42b94ccd792b8c9 to your computer and use it in GitHub Desktop.
git checkout で cd - のようにする

git checkout で cd - のようにする

main(master) と他のブランチを切り替えているときに、「cd - みたいに直前のブランチに切り替える方法はないか?」と思って調べてみたメモ。

試しに git checkout - を実行したら出来てしまった。

$ git branch
  csb-twlq0
* main

$ git checkout -
Switched to branch 'csb-twlq0'
Your branch and 'origin/csb-twlq0' have diverged,
and have 2 and 2 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

$ git branch
* csb-twlq0
  main

$ git checkout -
Switched to branch 'main'
Your branch is up to date with 'origin/main'.

$ git branch
  csb-twlq0
* main

git checkout <branch><branch>@{-N} が使えて、さらに -@{-1} として使えるということらしい。 man git-checkout からの抜粋。

<branch>

Branch to checkout; if it refers to a branch (i.e., a name that, when prepended with "refs/heads/", is a valid ref), then that branch is checked out. Otherwise, if it refers to a valid commit, your HEAD becomes "detached" and you are no longer on any branch (see below for details).

You can use the @{-N} syntax to refer to the N-th last branch/commit checked out using "git checkout" operation. You may also specify - which is synonymous to @{-1}.

また、@{-N}git checkout の操作ログになるので(ここは要確認)、commit していても1つ前の git checkout の切り替え元に切り替えられるもよう。

$ git branch
* main
  topic/test-switch

$ git checkout topic/test-switch
Switched to branch 'topic/test-switch'

$ vim README.md

$ git add README.md

$ git commit -m 'test1'
[topic/test-switch 390f688] test1
 1 file changed, 1 insertion(+)

$ vim README.md

$ git add README.md

$ git commit -m 'test2'
[topic/test-switch 4398274] test2
 1 file changed, 1 insertion(+)

$ git checkout -
Switched to branch 'main'
Your branch is up to date with 'origin/main'.

$ git reflog
345c6ac (HEAD -> main, origin/main, origin/HEAD) HEAD@{0}: checkout: moving from topic/test-switch to main
4398274 (topic/test-switch) HEAD@{1}: commit: test2
390f688 HEAD@{2}: commit: test1
345c6ac (HEAD -> main, origin/main, origin/HEAD) HEAD@{3}: checkout: moving from main to topic/test-switch

  <snip>

$ git branch
* main
  topic/test-switch

License: CC0 1.0 http://creativecommons.org/publicdomain/zero/1.0/deed.ja

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment