【git】git远程仓库迁移后 本地批量修改远程地址
当公司迁移远程git仓库时,我们需要修改git仓库的远程仓库的地址,可以一个一个的修改,但是如果项目比较多并且改的东西都一样的话,使用脚本修改就比较方便了。
预备知识:
查看远程仓库地址:
git remote -v
如
node@ykt03:~/rainclassroom/egg-web$ git remote -v
origin http://10.9.8.99/nodejs/egg-web.git (fetch)
origin http://10.9.8.99/nodejs/egg-web.git (push)
获取远程仓库地址:
git remote get-url origin
node@ykt03:~/rainclassroom/egg-web$ git remote get-url origin
http://10.9.8.99/nodejs/egg-web.git
这里需要考虑特殊情况:
即:有些git版本没有 git remote get-url origin
函数,获取不了原来的仓库地址的格式,就通过变通的方式获取。
git remote -v | head -n 1 | cut -d " " -f 1 | cut -c 8-
解读:
- 通过
git remote -v
获取两行的远程信息- 通过
head -n 1
只取第一行- 通过
cut -d " " -f 1
得到origin http://10.9.8.99/nodejs/egg-web.git
, 因为origin
和http
中间的可能不是个空格- 通过
cut -c 8-
得到http://10.9.8.99/nodejs/egg-web.git
修改本地仓库的远程地址:
方法一:
git remote set-url origin
node@ykt03:~/rainclassroom/egg-web$ git remote set-url origin http://10.9.8.99/nodejs/egg-web.git
方法二:
也可以通过 git config -e
,进入编辑器修改,这里可以修改更多东西。 查看git配置也可以通过 git config -l
查看,查看全局配置可以通过 git config --global -l
查看。
实战:
实战一:通过批量替换ip的方式来实现修改本地仓库对应的远程地址
首先进入包含所有项目的那个文件夹。 然后执行下面3行脚本即可。
export GIT_HOST_OLD=117.79.83.55:8088
export GIT_HOST=10.9.8.99
ls -l -d */ | awk '{print $9}' | xargs -I % bash -c ' cd % && if [ -d ".git" ]; then url=$(git remote get-url origin); git remote set-url origin ${url/$GIT_HOST_OLD/$GIT_HOST}; fi; '
解读:
先通过两个
export
设置两个变量,使其可以在子bash中使用。第三行的解释如下:
- 通过
ls -l -d */
列出所有目录- 通过
awk '{print $9}'
找到目录名称- 通过
xargs
将输出作为参数传给bash -c
(这里使用bash
是因为使用sh
的话在有些环境执行后面的替换${var-a/var-b/var-c}
的时候会失败)。并通过xargs -I %
将%
作为输入的占位符传给后面的bash -c
命令。- 后面的就是
bash
命令了,先切换到该次输入值的目录,如果有.git
文件夹,就先获取原来的git仓库地址,然后设置仓库地址为将原来地址的host:port部分替换后的变量。这样容易保留原来的格式。
实战二:用变量来存储相同的地址
把相同的仓库地址放到 /etc/hosts
中,替换仓库地址为其中的变量即可,而不用具体的ip的值,以后仓库再改变的话,只需要改 /etc/hosts
即可。
export GIT_HOST_OLD=10.9.8.99
export GIT_HOST=gitlab
ls -l -d */ | awk '{print $9}' | xargs -I % bash -c ' cd % && if [ -d ".git" ]; then url=$(git remote -v | head -n 1 | cut -d " " -f 1 | cut -c 8-);git remote set-url origin ${url/$GIT_HOST_OLD/$GIT_HOST}; fi; '
参考 /etc/hosts
中的内容如下:
➜ ~ cat /etc/hosts
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
192.168.9.198 hit.xuetangx.com
192.168.9.198 studio-hit.xuetangx.com
192.168.9.187 fudan.xuetangx.com
192.168.9.187 studio-fudan.xuetangx.com
192.168.9.246 fzu.xuetangx.com
192.168.9.246 studio-fzu.xuetangx.com
xx.80.178.83 build.ykt.io
192.168.9.99 gitlab
参考:https://juejin.cn/post/6885164439146872845