LoginSignup
0
1

More than 1 year has passed since last update.

git reset と git checkout って何が違うの?

Posted at

こんにちは。
先日タイトルの2つの違いがわからなかったので、色々調べた。
実務で使ったことないので、ズレは正直あるかもしれないが、今の理解をまとめる場とする。
また、ごちゃつかないように、端的にを意識して記述している。

どこで使うか

この2つのコマンドは「インデックスやワークツリーの①何かを②何かの状態に戻すとき」に使われる。

①と②はそれぞれ下記の候補が出てくる。


- 特定のファイル
- 全てのファイル


- HEAD or インデックス
- 過去のコミット

各コマンドをgit helpで見ると

git reset --help

NAME
       git-reset - Reset current HEAD to the specified state

SYNOPSIS
       git reset [-q] [<tree-ish>] [--] <pathspec>...
       git reset [-q] [--pathspec-from-file=<file> [--pathspec-file-nul]] [<tree-ish>]
       git reset (--patch | -p) [<tree-ish>] [--] [<pathspec>...]
       git reset [--soft | --mixed [-N] | --hard | --merge | --keep] [-q] [<commit>]

DESCRIPTION
       In the first three forms, copy entries from <tree-ish> to the index. In the last form, set the
       current branch head (HEAD) to <commit>, optionally modifying index and working tree to match. The
       <tree-ish>/<commit> defaults to HEAD in all forms.

要約すると、

  1. HEADからインデックスへコピーをし、オプションで作業ツリーへコピーする。
  2. HEADを指定のコミットに移動し、オプションで移動先のコミットからインデックスとワークツリーへコピーする。

もっと簡単に言えば、今のHEADを特定された状態へ移動し、それをオプションでインデックスとワークツリーにコピーする。
オプションとは

  1. --hard : インデックスとワークツリーに反映(今あるファイルが指定されたHEADに同期されるので注意)
  2. --mixed(default) : インデックスのみに反映
  3. --soft : 反映しない。(HEADだけが動く。)

git checkout --help

NAME
       git-checkout - Switch branches or restore working tree files

SYNOPSIS
       git checkout [-q] [-f] [-m] [<branch>]
       git checkout [-q] [-f] [-m] --detach [<branch>]
       git checkout [-q] [-f] [-m] [--detach] <commit>
       git checkout [-q] [-f] [-m] [[-b|-B|--orphan] <new_branch>] [<start_point>]
       git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <pathspec>...
       git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] --pathspec-from-file=<file> [--pathspec-file-nul]
       git checkout (-p|--patch) [<tree-ish>] [--] [<pathspec>...]

DESCRIPTION
       Updates files in the working tree to match the version in the index or the specified tree. If no
       pathspec was given, git checkout will also update HEAD to set the specified branch as the current
       branch.

要約すると

  1. ワークツリーのファイルをインデックス、ま他は指定されたコミットのバージョンと一致させる。

違いのキーワード

  • reset
    • 過去のコミットから反映させるとき
    • インデックスのみの変更
  • checkout
    • ワークツリーまで変更する。
    • ワークツリー・インデックス・HEADの3つを一致させる。
    • 過去のコミットからの状態を「試したい」とき。
      • ブランチに影響を与えたくないとき。

図でまとめた

スクリーンショット 2021-05-12 7.03.25.png

ここまで理解すれば、あとは実践あるのみだと私は感じている。
今後実務で更新点があれば随時行っていこうと思う。
実務で使っている方でぜひ違う場所や、アドバイスがあればいただきたい。

以上。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1