Git 学習メモ

📢 この記事は ChatGPT によって翻訳されました

自分が学んだ Git の内容をまとめておくよ。

1. インストール

Windows に Git をインストール

公式サイトからダウンロード: https://git-scm.com/download/win
インストール後、Git Bash を一度起動しておく。

Linux に Git をインストール

  • Debian: sudo apt-get install git
  • Fedora: dnf install git
  • CentOS: yum install git

他は公式参照: https://git-scm.com/download/linux

macOS に Git をインストール

Homebrew 経由でインストールするのが一般的。詳細: http://brew.sh/

または、AppStore で Xcode をインストール → Xcode を開いて
Xcode > Preferences > Downloads > Command Line Tools を選んでインストール。

2. 初期設定

インストール直後、以下でユーザー情報を設定:

1
2
git config --global user.name "Your Name"
git config --global user.email "[email protected]"

3. リポジトリの作成

適当なフォルダで以下を実行:

1
git init

これで .git フォルダができ、Git 管理の対象になる。中は直接編集しないこと。


リモートリポジトリのクローン

他人のリポジトリ

1
git clone https://github.com/yexca/typecho-theme-book.git

コミット権限がないなら HTTPS で問題なし。編集・プルリクしたいなら自分のリポジトリへ fork しよう。

自分のリポジトリ(SSH)

事前に GitHub の SSH キー設定: https://github.com/settings/keys その後:

1
git clone [email protected]:yexca/typecho-theme-book.git

参考:

4. ファイルのコミット(ローカル)

ファイル変更後:

1
2
3
git add filename
# すべて追加する場合
git add .

追加後、コミット:

1
git commit -m "変更内容の説明"

.gitignore で除外ファイルを設定

例:

1
2
3
test/         # testフォルダ
*.py[cod]     # .pyc, .pyo, .pyd
!app.pyc      # app.pycだけ除外しない

無視してても強制追加可:

1
git add -f test.pyc

.gitignore 変更時はキャッシュクリアが必要:

1
2
3
git rm -r --cached .
git add .
git commit -m "update .gitignore"

5. 状態確認と取り消し

1
2
3
4
git status      # 状態確認
git diff        # 差分表示
git log         # コミット履歴
git log --pretty=oneline

バージョンを戻す

  • 一つ前:git reset --hard HEAD^
  • 特定のバージョンへ:
1
git reset --hard コミットID(先頭数桁でもOK)

戻しすぎた場合は:

1
git reflog

でログを確認して戻す。

6. GitHub にリンク

GitHub 上でリポジトリを作成後:

1
git remote add origin [email protected]:username/repo.git

ローカルで編集したら:

1
git push origin master

main/master の違い

VS Code は master を使うが GitHub は main。 変更したい場合:

1
git branch -m master main

初期ブランチを main に設定:

1
git config --global init.defaultBranch main

毎回 --set-upstream するのが面倒なら:

1
git push --set-upstream origin main

以降は git push origin だけで OK。

リモートの再設定

1
2
git remote -v     # 確認
git remote rm origin  # 削除

7. ブランチ操作

1
2
3
4
5
git branch               # 一覧
git branch new_branch    # 作成
git switch new_branch    # 切り替え
git checkout new_branch  # 同上
git push origin new_branch  # プッシュ

ブランチ作って機能開発 → main にマージする流れ:

1
2
3
4
5
git switch -c search
# ...編集、テスト、コミット...
git switch main
git merge search
git branch -d search

8. Git サーバー構築

参考: Gitサーバーを構築し、指定ディレクトリに同期する方法

9. その他

GitLab & GitHub 両方使いたい人向け:

Git 同期設定(GitLab + GitHub)

参考資料

This post is licensed under CC BY-NC-SA 4.0 by the author.
最終更新 2025-01-03 22:33 +0900

Visits Since 2025-02-28

Hugo で構築されています。 | テーマ StackJimmy によって設計されています。