/Linuxコマンド

開発ツール

Git と GitHub CLI

git の毎日使う操作と、困ったときの戻し方。gh で GitHub の操作をターミナルから行う。

gitバージョン管理

ファイルの変更履歴を管理するバージョン管理システムです。チームでの開発に欠かせません。

最初の設定

bash
$ git config --global user.name "Your Name"
$ git config --global user.email "[email protected]"
$ git config --global init.defaultBranch main
$ git config --global core.autocrlf input    # WSL では改行を LF に揃える
$ git config --list

毎日の流れ

bash
$ git clone https://github.com/user/repo.git
$ git status                     # 変更の状況
$ git switch -c feature/login    # ブランチを作って移る
$ git add -p                     # 変更を少しずつ選んでステージ
$ git add .                      # すべてステージ
$ git commit -m "ログイン画面を追加"
$ git pull --rebase              # 最新を取り込む
$ git push -u origin feature/login

見る

bash
$ git log --oneline --graph --all -20
$ git log -p -- path/to/file     # そのファイルの変更履歴
$ git diff                       # まだステージしていない変更
$ git diff --staged              # ステージした変更
$ git show HEAD~1                # 1つ前のコミット
$ git blame -L 10,20 main.go     # 行ごとに最後に変えた人
$ git grep "TODO"                # 管理しているファイルから探す

ブランチ

bash
$ git branch -a                  # すべてのブランチ
$ git switch main
$ git merge feature/login
$ git rebase main                # 今のブランチを main の先頭に付け替える
$ git branch -d feature/login    # マージ済みのブランチを消す
$ git push origin --delete feature/login

一時退避

bash
$ git stash                      # 変更を一時的にしまう
$ git stash list
$ git stash pop                  # 戻す

取り消す・戻す

やりたいことコマンド
ファイルの変更を捨てるgit restore <ファイル>
ステージを取り消すgit restore --staged <ファイル>
直前のコミットのメッセージを直す・追加し忘れを足すgit commit --amend
直前のコミットを取り消す(変更は残す)git reset --soft HEAD~1
公開済みのコミットを打ち消すgit revert <コミット>
消してしまったコミットを探すgit reflog

ghGitHub をターミナルから操作する

Ubuntu には最初から入っていません。 で入れられます。

GitHub のプルリクエストや Issue、Actions などをターミナルから操作します。

bash
$ gh auth login                  # 最初にログイン
$ gh repo clone owner/repo
$ gh repo create my-app --private --source=. --push
$ gh pr create --fill            # 今のブランチからPRを作る
$ gh pr list
$ gh pr checkout 42              # PR #42 を手元に持ってくる
$ gh pr merge 42 --squash
$ gh issue list --label bug
$ gh issue create -t "タイトル" -b "本文"
$ gh run list                    # Actions の実行一覧
$ gh run watch                   # 実行中のActionsを見守る
$ gh release create v1.0.0 ./dist/*
$ gh browse                      # リポジトリをブラウザで開く