Gitの使い方

Gitの使い方についてTerminalを使って解説していきたいと思います。

初期設定

まずは初期設定から。ブランチ名はデフォルトでmasterになります。

$ mkdir git_work
$ cd git_work/

$ git init
Initialized empty Git repository in /Users/nokkun/Desktop/git_work/.git/

$ git status
On branch master

No commits yet

nothing to commit (create/copy files and use "git add" to track)

ステージング

次にファイルを追加してステージングエリアに追加します。

$ touch hogefile

$ git status
On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
	hogefile

nothing added to commit but untracked files present (use "git add" to track)

$ git add hogefile

$ git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
	new file:   hogefile

コミットする

コミットしてログを確認します。

$ git commit -m "first commit"
[master (root-commit) a8f8d0e] first commit
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 hogefile

notsukunnoMacBook-Pro-10:git_work nokkun$ git log
commit a8f8d0eb8ba82941c4d11e8700bf9bb145eb626f (HEAD -> master)
Author: nokkun <at.mc1.18@gmail.com>
Date:   Thu Sep 1 08:38:03 2022 +0900

    first commit

gitignoreの設定

管理対象外にしたいファイルをgitignoreに設定してみます。

$ git status
On branch master
nothing to commit, working tree clean

$ touch kanrigai

# kanrigaiファイルが追加された。
$ git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)
	kanrigai

$ touch .gitignore

# .gitignoreにkanrigaiを追加します。
$ open .gitignore

# gitの管理から外れました。
$ git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)
	.gitignore

# gitignoreもコミットしておきます。
$ git add .gitignore
$ git commit -m "make .gitignore"

リモートリポジトリへPushする

GithubのリモートリポジトリにPushしてみたいと思います。

Githubにブラウザでアクセスしてリポジトリを作成します。

github

リモートレポジトリを追加します。

# originという名前で追加する
$ git remote add origin https://github.com/age0319/PushTest.git

# 確認
$ git remote -v
origin	https://github.com/age0319/PushTest.git (fetch)
origin	https://github.com/age0319/PushTest.git (push)

# Pushする。リモート名 ブランチ名の順番で指定する。
$ git push origin master
Enumerating objects: 6, done.
Counting objects: 100% (6/6), done.
Delta compression using up to 4 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (6/6), 453 bytes | 453.00 KiB/s, done.
Total 6 (delta 0), reused 0 (delta 0)
To https://github.com/age0319/PushTest.git
 * [new branch]      master -> master

ABOUTこの記事をかいた人

個人アプリ開発者。Python、Swift、Unityのことを発信します。月間2.5万PVブログ運営。 Twitter:@yamagablog