HOWTO · Git

Git でブランチを作成して使用する

このチュートリアルでは、Git ブランチを紹介します。Git ブランチがプロジェクトの整理にどのように役立つかを見ていきます。

このページの内容

このチュートリアルでは、Git ブランチを紹介します。Git ブランチがプロジェクトの整理にどのように役立つかを見ていきます。

扱うコマンドには、git branchgit checkout があります。

Git で git branch コマンドを使用してブランチを作成、表示、削除する

git branch コマンドを使用して、ブランチを作成、表示、および削除します。

このコマンドを使用して、異なるブランチを切り替えることはできません。

  1. git ブランチには、リポジトリ内のすべてのブランチが表示されます。
  2. git branch <branch name> は、リポジトリに新しいブランチ <branch name> を作成します。
  3. git branch -d <branch name> はブランチ <branch name> を削除します。このコマンドを実行する前に、まず変更をマージします。
  4. git branch -D <branch name> は、例外なくブランチを削除します。決定に前向きな場合は、このコマンドを使用してください。
  5. git branch -m <branch name> は、ブランチの名前を変更または移動します。

New_Branch という新しいブランチを作成しましょう。

pc@JOHN MINGW64 ~/Git (main)
$ git branch New_Branch

ブランチが存在するかどうかを確認します。

pc@JOHN MINGW64 ~/Git (main)
$ git branch
  New_Branch
* main

上記の出力から、New_Branchmain の 2つのブランチがあります。

New_Branch を削除してみましょう。

pc@JOHN MINGW64 ~/Git (main)
$ git branch -d New_Branch
Deleted branch New_Branch (was 78129a6).

変更をマージしないと、エラーメッセージが表示されます。git push origin --delete <branch name> を使用して、リモートリポジトリからブランチを削除します。

git checkout -b <branch> を使用して、Git の現在の変更を含む新しいブランチを作成する

git checkout コマンドは、プロジェクト内のブランチを切り替えます。

リポジトリ内の既存のブランチを確認するには、git checkout <branch> を使用します。以下に例を示します。

$ git branch
  Last_Branch
  New_Branch
* main
pc@JOHN MINGW64 ~/Git (main)
$ git checkout New_Branch
Switched to branch 'New_Branch'
M       .bash_history
M       text.txt.txt
M       text.txt.txt.bak

上記のコードには、New_BranchLast_Branch の 2つのブランチがあります。git checkout New_Branch を使用して、main ブランチから New_Branch に切り替えます。

git checkout -b <branch> を使用して、新しいブランチに切り替えます。例を見てみましょう。

pc@JOHN MINGW64 ~/Git (New_Branch)
$ git checkout -b Branch1
Switched to a new branch 'Branch1'

新しいブランチに切り替えると、Git は現在のブランチから新しいブランチへの変更を自動的に保存します。これをチェックしてください。

pc@JOHN MINGW64 ~/Git (Branch1)
$ git status
On branch Branch1
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   .bash_history
        modified:   text.txt.txt
        modified:   text.txt.txt.bak
Untracked files:
  (use "git add <file>..." to include in what will be committed)
        .bash_history.bak
no changes added to commit (use "git add" and/or "git commit -a")

上記の出力は、Git が main ブランチから Branch1 への変更を保存したことを証明しています。