Linux Mac シェルコマンド プログラミング

gitの基本コマンド

よく使いそうなコマンド

gitはあんまり使ってないです。

使ってないから覚えられないのか、覚えてないから使わないのか、たぶん両方なんだと思います。

しかし、やっぱり使えた方が良いので、とりえあえずコマンドをまとめました。

一応試しながら書きましたが、間違っている可能性もあります。随時追加予定。

現在のディレクトリのgit管理を開始
  git init

変更のあったファイルをすべてステージング(コミット予定リストに追加)
  git add . 

ステージングされたファイルをコミット
  git commit -m "メッセージ" 

ブランチの作成
  git branch {ブランチ名}

ブランチの切り替え
  git checkout {ブランチ名} 

{ブランチ名}の内容を現在のブランチにマージ
  git merge {ブランチ名}

現在のステータス表示
  git status

設定確認
  git config -l 

リモートリポジトリ関係

リモートリポジトリ(GitHub)の登録
  git remote add origin {アドレス(GitHub)}

リモートリポジトリにプッシュ
  git push -u origin {ブランチ名} 
// -u オプションを付けると次回以降は origin とブランチ名が省略可能になる

リモートリポジトリの登録解除
  git remote rm origin

リモートリポジトリの確認
  git remote -v

リモートリポジトリ(GitHub)からクローン
git clone {SSH clone adress}

変更の取消

ステージングの取消
  git reset {ファイル名} //特定ファイルのステージングだけ取消。中身は変わらない
  git reset .         //全ファイルのステージングだけ取消。中身は変わらない

ステージングしたところまで戻す
  git checkout -- {ファイル名} //特定ファイルの中身をステージングしたところまで戻す
  git checkout .            //すべてのファイルをステージングしたところまで戻す

HEAD(最後のコミット)まで戻す
  git checkout HEAD -- {ファイル名} //特定のファイルのみ戻す
  git checkout HEAD .            //すべてのファイルを戻す

あと、git reset で hardとかsoftとかHARDとかあるのですが、よく分かりません。

コミットの巻き戻し

ログを表示(コミットIDを表示)
  git log

過去のコミットまで戻す
  git reset --hard {コミットID} //コミットID以降は無かったことにする
  git revert {コミットID}       //コミットIDまで"戻った"という履歴が残る

過去のコミットを使って新しいブランチを作成

git logでコミットIDを確認

git checkout {コミットID}

こうするとコミットIDを名前にした仮のブランチが作られて、そこに移動します。

このブランチは他のブランチにcheckoutすると消えてしまうみたいです。

こんなメッセージがでます。

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

このブランチで編集してコミットしてから、mainに戻ると以下のようなメッセージがでます。

git checkout main
Warning: you are leaving 1 commit behind, not connected to
any of your branches:

  1c3fb98 detatched branch

If you want to keep it by creating a new branch, this may be a good time
to do so with:

 git branch <new-branch-name> 1c3fb98

仮のブランチはコミットしても消えてしまうようなので、

git branch {新ブランチ名} {仮ブランチ名}

とすると、正式なブランチに昇格するみたいです。

デフォルトブランチ名の変更

いつのまにかデフォルトブランチの名前がmasterからmainとかに変わっていました。

これを変更するためのコマンドです。

コンフィグの書き換え
  git config --global init.defaultBranch main

すでに作っちゃったリポジトリの変更
  git branch -m main

ユーザーIDとメールアドレスの設定

名前とメアドが無いと怒られます。

    git config --global user.name "Your Name"
    git config --global user.email you@example.com

    git commit --amend --reset-author

-Linux, Mac, シェルコマンド, プログラミング