背景
有时候我们需要修改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 仓库地址可以通过 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 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
查看。
脚本批量修改
执行步骤
首先进入包含所有项目的那个文件夹。 然后执行下面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部分替换后的变量。这样容易保留原来的格式。
特殊情况
有些git版本没有 git remote get-url origin
函数,获取不了原来的仓库地址的格式,就通过变通的方式获取。如下:
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 -v | head -n 1 | cut -d " " -f 1 | cut -c 8-);git remote set-url origin ${url/$GIT_HOST_OLD/$GIT_HOST}; fi; '
改变的地方
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
小坑
有人可能想为什么不继续用 awk '{print $2}'
而用 cut
呢,是因为 awk
只能用单引号,跟最外层的单引号有冲突,下次有时间继续研究的话再在这里补充。
进阶
其实可以把相同的仓库地址放到 /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