克隆到非空 Git 目錄

John Wachira 2022年4月22日
克隆到非空 Git 目錄

本文將介紹如何將 Git 倉庫克隆到非空資料夾。當你要將遠端倉庫中的檔案與當前本地倉庫中的檔案合併時,此操作會派上用場。

在 Git 中克隆到非空 Git 目錄

克隆遠端倉庫很容易。我們使用下面的命令。

git clone <repository-url> <directory>

這會將遠端倉庫克隆到指定目錄。但是,該目錄應該是空的。

如果你嘗試在非空倉庫中克隆,你將收到致命警告訊息,如下所示。

pc@JOHN MINGW64 ~/Git (main)
$ git clone https://github.com/Wachira11ke/Delftscopetech.git
fatal: destination path 'Delftscopetech' already exists and is not an empty directory.

由於目錄 Delftscopetech 已經存在幷包含一些檔案,我們不能使用 git clone 命令來克隆我們的倉庫。

如果你不需要目錄中的檔案,你可以刪除它們,但如果你想合併兩個倉庫中的檔案,請使用下面的方法。

  1. 開啟你要將遠端倉庫克隆到的目錄。

    ``bash
    cd / Delftscopetech1

  2. 使用此命令設定新倉庫。

    git init
    
  3. 新增遠端倉庫

    git remote add origin https://github.com/Wachira11ke/Delftscopetech.git
    
  4. 拉取合併

    git pull origin main --allow-unrelated-histories
    

例子:

pc@JOHN MINGW64 ~/Git (main)
$ cd \Delftscopetech1

pc@JOHN MINGW64 ~/Git/Delftscopetech1 (main)
$ git init
Initialized empty Git repository in C:/Users/pc/Git/Delftscopetech1/.git/

pc@JOHN MINGW64 ~/Git/Delftscopetech1 (master)
$ git remote add origin https://github.com/Wachira11ke/Delftscopetech.git

pc@JOHN MINGW64 ~/Git/Delftscopetech1 (master)
$ git pull origin master --allow-unrelated-histories
fatal: couldn't find remote ref master

pc@JOHN MINGW64 ~/Git/Delftscopetech1 (master)
$ git pull origin main --allow-unrelated-histories
remote: Enumerating objects: 3, done.
remote: Counting objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), 610 bytes | 3.00 KiB/s, done.
From https://github.com/Wachira11ke/Delftscopetech
 * branch            main       -> FETCH_HEAD
 * [new branch]      main       -> origin/main

我們已經成功地將我們的遠端倉庫克隆到了我們的本地倉庫中,並使用了一個非空目錄。

作者: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

相關文章 - Git Clone