LoginSignup
0
0

Git フェッチとプル

Last updated at Posted at 2023-05-17

テスト用環境の作成

最初に以下のコマンドでリポジトリをコピーし、自分のリポジトリにプッシュしてください。

$ git clone https://github.com/Kasumin0123/git_test.git
$ cd git_test
$ git remote add myrepo <URL>
$ git push -u myrepo master

リモートリポジトリを追加する

リモートリポジトリは複数登録することができる。

$ git remote add <リモート名> <URL>

リモートを確認する

$ git remote
# リモート名のみが表示される

$ git remote -v
# リモート名と対応するURLが表示される

リモートから情報を取得する

リモートから情報を取得するには

  • fetch
  • pull

の2種類の方法がある。

fetch

$ git fetch <リモート名>

試しに、originにファイルを追加しよう。GitHubのサイトからリポジトリ(myrepo)を開いて、Add file > Create new fileを選択してファイルを作成する。ファイルには以下のように記述する。

home.html
<p>home</p>

ファイルを作成したら、フェッチしよう。

$ git fetch myrepo

フェッチが完了したら、以下のコマンドを打ち込んでみよう。

$ git branch -a
* master
  remotes/myrepo/master
  remotes/origin/HEAD -> origin/master
  remotes/origin/main
  remotes/origin/master

remotes/myrepo/masterというブランチ(リモートブランチという)に、フェッチした内容が入っている。実際にファイルの中身を確認するため、以下のコマンドを入力してみよう。

$ git checkout myrepo/master
Note: checking out 'remotes/myrepo/master'.

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 performing another checkout.

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

  git checkout -b <new-branch-name>

HEAD is now at 6419fe6 Create home.index
# ワークツリーが変更されたのでlsコマンドで確認する
$ ls
home.html  index.html
# home.htmlが追加されている。catコマンドで中身を見る。
$ cat home.html
<p>home</p>


では、元の状態に戻そう。

$ git checkout master
Previous HEAD position was 6419fe6 Create home.index
Switched to branch 'master'
Your branch is behind 'myrepo/master' by 1 commit, and can be fast-forwarded.
  (use "git pull" to update your local branch)

最後に、取得してきたリモートリポジトリの情報をワークツリーに取り込んで終了しよう。

$ git merge myrepo/master
Updating 2d5ae52..6419fe6
Fast-forward
 home.index | 1 +
 1 file changed, 1 insertion(+)
 create mode 100644 home.index
$ ls
home.html  index.html
# ファイルが追加されていることが分かる

pull

$ git pull <リモート名> <ブランチ名>

# これは下記コマンドと同じ
$ git fetch <リモート名>
$ git merge <リモート名>/<ブランチ名>

$ git pull origin master
# は、以下のように省略できる
# git pull

fetchとpullの使い分け

pullは楽だが、プルしたブランチは今いるブランチに強制的にマージされるのでワークツリーがぐちゃぐちゃになる可能性がある。慣れるまではfetchしてからmergeするという手順を踏んだ方がいい。

リモートの詳細情報を表示する

$ git remote show <リモート名>

リモート名の変更・削除

リモート名を変更するには以下のコマンドを使う。

$ git remote rename <旧リモート名> <新リモート名>

リモートを削除するときには以下のコマンドを使う。

$ git remote rm <リモート名>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0