[TOC] #### 1. 使用场景 --- 看完本文内容可解决以下问题: 1、本地代码需要上传到远程仓库上时 2、本地已有仓库,需要将本地仓库推送到远程仓库上时 3、本地已有仓库,并且已关联远程仓库,需要更改关联的远程库时 #### 2. 推送代码流水线 --- ``` # 第一步: 创建本地库并完成初始提交,也就是让本地库有提交记录 git init git add . git commit -m "first commit" # 第二步: 添加一个远程仓库配置 git remote add origin https://gitee.com/holyking/test-1.git # 第三步: 设置上游分支,并且使用远程名称推送到远程库 git push -u origin master ``` #### 3. 添加远程库配置 ---- 首次将代码推送到远程仓库出现以下提示:  ``` # 没有配置推送目标 fatal: No configured push destination. # 从命令行指定 URL,或使用配置远程存储库 Either specify the URL from the command-line or configure a remote repository using # 然后使用远程名称推送 and then push using the remote name ``` 从命令行指定 URL ``` # 命令格式 git push <url> <branch> # 使用示例 git push git@gitee.com:holyking/test-1.git master ``` 先配置一个远程存储库,然后使用远程名称推送(其实就是给远程库 url 起了一个比较短的名称,然后使用短名称推送) ``` # 命令格式 git remote add <name> <url> git push <name> <branch> # 使用示例 git remote add origin git@gitee.com:holyking/test-1.git git push origin master ``` #### 4. 修改远程库配置 --- **如果本地仓库已经关联过远程仓库,使用 `git remote add` 直接关联新的远程库时会报错** ``` fatal: remote origin already exists. ```  **解决方案1: 先删除以前的远程仓库关联关系,再关联新的远程仓库** ```bash git remote rm origin git remote add origin https://gitee.com/holyking/test-3.git ```  **解决方案2: 使用 git remote set-url origin 直接修改关联的远程仓库** ```bash # 使用前提: 远程名称 origin 已存在 git remote set-url origin https://gitee.com/holyking/test-3.git ``` **修改关联的远程仓库总结:** ``` # 方案1: 先删除远程库配置,再重新添加 git remote rm <name> git remote add <name> <url> # 方案2: 使用 set-url 直接修改 git remote set-url <name> <url> ``` #### 5. 删除远程库配置 ---- 删除远程库配置 ``` # 命令格式 git remote remove <name> # 使用示例 git remote remove origin ``` 经测试 `rm`、`remove` 的作用是一样的,所以也可以使用下面用法 ``` git remote rm <name> ``` #### 6. 重命名远程库配置 --- ``` # 命令格式 git remote rename <old> <new> # 使用示例 git remote rename origin liang ``` #### 7. 推送到多个仓库 --- 添加远程库配置(我们要将代码推送到 gitee 和 github 两个平台) ``` # gitee git remote add gitee git@gitee.com:holyking/test-1.git # github git remote add github git@github.com:shinyboys/test-2.git ``` 将代码推送 gitee 和 github ``` git push gitee master && git push github master ``` 推送到远程库时,因为命令有点长,我们可以定义一个系统配置别名,进而简化推送命令 ``` # mac 用户可以在 ~/.zshrc 文件中增加以下配置,通过别名 gp 推送 alias gp="git push gitee master && git push github master" ``` #### 8. 查看远程库配置 --- 不带参数时,就是列出已存在的远程分支 ``` git remote ``` `-v,--verbose` 查看所有远程仓库配置 ``` git remote -v ``` #### 9. 查看远程库信息以及和本地库的关系 --- 这个命令会联网去查询远程库信息,并且会列出和本地库的关系 ``` # 命令格式 git remote show <name> # 使用示例 git remote show origin ```