Git(Hub) の使い方

レポジトリの作成・管理

  • まだどこにも存在しない新規 git レポジトリをローカルに作成
    • $ cd ディレクトリ名; git init
  • GitHub 等に存在する(自分の・他人の)リモートレポジトリをローカルにコピー
    • $ git clone URL
    • submodule も一緒に取得したい場合は--recursiveをつける
  • 現在のリモートリポジトリ一覧表示
    • $ git remote -v
  • リモートレポジトリを追加
    • $ git remote add エイリアス名 URL
    • URLhttps プロトコル (例: https://github.com/ユーザ名/レポジトリ名) か ssh プロトコル (例: git@github.com:ユーザ名/レポジトリ名) のどちらか
      • ssh プロトコルだと git push した際にパスワード認証が不要
      • ~/.gitconfig に以下のように記述しておくと、URL のプロトコルを自動で https から ssh に変えてくれる
[url "git@github.com:"]
        insteadof = https://github.com/
  • リモートレポジトリの URL を変更
    • $ git remote set-url エイリアス名 URL

レポジトリの状態の管理

  • 変更状況を確認
    • $ git status
  • ログツリーを表示
    • $ git log --oneline --graph --decorate
    • .bash_profile に以下のように記述しておくと $ git log だけで済む
git() {
    if [[ $@ == "log" ]]; then
        git log --oneline --graph --decorate
    else
        command git "$@"
    fi
}
  • ブランチの一覧表示
    • $ git branch

変更の反映

  • ローカル上の変更をリモートレポジトリに反映
    • $ git add .; git commit -m "コミットメッセージ"; git push
    • fatal: The current branch master has no upstream branch. と表示されたら $ git push origin master
  • リモートレポジトリを指定してプッシュ
    • $ git push -u エイリアス名
  • リモートレポジトリ上の変更をローカルに反映
    • $ git pull (origin master)

ブランチ

  • 新規ブランチの作成
    • $ git branch ブランチ名
  • ブランチの移動
    • $ git checkout ブランチ名

サブモジュール

  • サブモジュールの追加
    • $ git submodule add URL
  • 最新の commit に更新
    • $ cd サブモジュールディレクトリ名; git pull origin master
    • $ cd レポジトリルート; git add/commit/push (これをするまでstatusは更新されない)

SSH接続

  • ~/.ssh/configGitHub に登録した公開鍵に対応する秘密鍵を指定しておく
Host github.com
     User ユーザ名
     HostName ssh.github.com
     IdentityFile ~/.ssh/秘密鍵ファイル名
     ServerAliveInterval 60
  • Gtk-WARNING **: cannot open display と表示されたら$ unset SSH_ASKPASS

.gitignoreファイル

  • 複数のディレクトリに置くことができる
  • 深い階層の.gitignoreに書かれた指定の方が優先順位が高い
  • 以下の上の行から順に解釈される
    • /を含まない、もしくは末尾以外にのみ/を含む行(e.g. file, /file, path/to/file, /path/to/file)
    • 末尾が/の行(e.g. /path/to/directory/, path/to/directory/)
    • !で始まる行(e.g. !/path/to/file)
      • !以降のパターン文字列が示すファイルまたはディレクトリを無視しない
      • 前の無視指定を上書きする
      • 以降の無視指定に上書きされうる
    • 空行もしくは#で始まる行
      • 解釈されない
  • ワイルドカード(*, ?, [0-9]など)も使える