Git 初心者向けガイド
対象:エンジニアになりたての方、Gitに興味がある初心者
Git とは?
チームで複数人がファイルを編集する際、誰かの変更が誰かの変更を上書きしてしまう問題が起こります。
Git は、大量のファイルを バージョン として管理し、複数人が安全に共同作業できるようにするためのツールです。
Gitの4つのエリア
| # | エリア | 説明 |
|---|---|---|
| 1 | Working Directory | 作業中のファイルが置かれる場所 |
| 2 | Staging Area | コミット前に変更をまとめる場所 |
| 3 | Local Repository | ローカルの変更履歴が保存される場所 |
| 4 | Remote Repository | GitHub などクラウド上の共有リポジトリ |
基本の流れ
編集 → git add → git commit → git push
環境の準備
Step 1 — Git をインストール
https://git-scm.com/ からダウンロード
# バージョン確認
git --version
Step 2 — ユーザー設定
git config --global user.name "Username"
git config --global user.email "email@example.com"
# 設定を確認
git config --list
Step 3 — リポジトリを初期化
git init
基本コマンド一覧
| コマンド | 説明 |
|---|---|
git add |
変更をステージングに追加 |
git commit |
変更を履歴に保存 |
git push |
リモートに送信 |
git fetch |
リモートの更新を取得 |
git pull |
fetch + merge(最新に同期) |
git restore |
変更を元に戻す |
git clone |
リモートをローカルにコピー |
git branch |
ブランチの作成・一覧表示 |
git checkout |
ブランチを切り替える |
よく使うコマンド例
# リポジトリをコピー
git clone https://github.com/user/project.git
# ブランチを作成して切り替え(旧)
git checkout -b feature-login
# ブランチを作成して切り替え(新)
git switch -c feature-login
# リモートの最新を取得
git pull
操作の取り消し対応表
操作の段階によって、取り消すコマンドが変わります。
| 状態 | 何をした? | 取り消すコマンド |
|---|---|---|
| Working Directory | ファイルを編集した | git restore <file> |
| Staging Area |
git add を実行した |
git restore --staged <file> |
| Local Repository |
git commit を実行した |
git reset --soft HEAD~1 |
| Remote Repository |
git push を実行した |
git revert <commit> |
1. 編集を取り消す
まだ git add していない場合、git restore で最後のコミット時の状態に戻ります。
git restore test.py
2. add を取り消す
git add した後にステージングを取り消したい場合。
ファイルは Staging Area から Working Directory に戻ります。
git restore --staged test.py
3. commit を取り消す
直前のコミットを取り消します。変更内容は残ります。
git reset --soft HEAD~1
4. push を取り消す
すでに git push した場合は、履歴を壊さない git revert が安全です。
指定したコミットを打ち消す新しいコミットを作成します。
git revert <commit-hash>
まとめ
編集を戻す → git restore
addを戻す → git restore --staged
commitを戻す → git reset --soft HEAD~1
pushを戻す → git revert
この流れを覚えることが、Git 理解の第一歩です。
編集 → git add → git commit → git push