git 动态设置用户信息
前因
在开发公司项目和个人项目都在同一个主机时出现一个很尴尬的问题,git
设置了user.name
和user.email
,在提交代码时难免出现个人项目使用公司的邮箱提交或者是公司项目用了个人的邮箱去提交,因为git
项目本地的设置只作用于这个项目,不会影响到其他项目,因此想了一个解决办法那就是在项目clone
到本地的时候根据域名设置项目本地的user.name
和user.email
实现脚本custom-clone.sh
#!/bin/bash
GREEN='\033[0;32m'NC='\033[0m'YELLOW='\033[0;33m'
# 检查是否提供了仓库URLif [ "$#" -ne 1 ]; then echo "Usage: custom-clone.sh <repository_url>" exit 1fi
# 获取仓库URLrepository_url="$1"
# 克隆仓库git clone "$repository_url"
# 进入克隆的仓库目录repository_name=$(basename "$repository_url" .git)cd "$repository_name"
git config --local user.name "xxx"
# 获取远程仓库的URLremote_url=$(git config --get remote.origin.url)
# 提取邮箱域名部分if [[ $remote_url =~ @(.+)$ ]]; then domain="${BASH_REMATCH[1]}" # 根据域名设置本地项目的邮箱地址 case "$domain" in *github.com*) echo -e "This domain is ${GREEN}github.com${NC}" echo -e "Set up user.name: ${GREEN}$(git config user.name)${NC}" echo -e "Set up user.email: ${GREEN}$(git config user.email)${NC}" ;; *xx.com*) echo -e "This domain is ${GREEN}xx.com${NC}" echo -e "Set up user.name: ${GREEN}$(git config user.name)${NC}" echo -e "Set up user.email: ${GREEN}$(git config user.email)${NC}" ;; *) # 设置一个默认邮箱地址,如果没有匹配的域名 echo -e "This domain unrecognized ${YELLOW}$domain${NC}" echo -e "Set up default user.name: ${GREEN}$(git config user.name)${NC}" echo -e "Set up default user.email: ${GREEN}$(git config user.email)${NC}" ;; esacfi
执行 chmod +x custom-clone.sh
增加执行权限
配置git
别名
- 编辑全局配置文件
git config --global --edit
- 设置别名
[alias] custom-clone = "!/path/to/custom-clone.sh"
- 保存设置
执行命令
git custom-clone url
一切配置好之后只需替换url
为实际项目地址就能实现拉取项目时根据配置的域名动态写入用户信息