Git 配置
1. config 的三个等级
这些设置存储在三个不同的位置:
/etc/gitconfig 文件: 包含系统上每一个用户及他们仓库的通用配置。如果使用带有 --system 选项的 git config 时,它会从此文件读写配置变量。
git config --system user.name "hfy"~/.gitconfig 或 ~/.config/git/config 文件: 只针对当前用户。 可以传递 --global 选项让 Git 读写此文件。
git config --global user.name "hfy"当前使用仓库的 Git 目录中的 config 文件(就是 .git/config):针对该仓库。
git config user.name "hfy"比如说公司项目和自己的项目的 user.name user.email 不是一套,可以单独根据项目设置,配合各自的 ssh key, push 到不同的平台,参见多个 SSH KEY 的管理
每一个级别覆盖上一级别的配置,所以 .git/config 的配置变量会覆盖 /etc/gitconfig 中的配置变量。
2. 增加 & 修改配置信息
配置用户名和邮箱
- 默认没有对应配置时
$ git config --global user.name "hfy" $ git config --global user.email "[email protected]"
注意git config命令的--global参数,用了这个参数,表示你这台机器上所有的Git仓库都会使用这个配置,当然也可以对某个仓库指定不同的用户名和Email地址。
如果使用了 --global 选项,那么该命令只需要运行一次,之后无论你在该系统上做任何事情, Git 都会使用那些信息。
当你想针对特定项目使用不同的用户名称与邮件地址时,可以在那个项目目录下运行没有 --global 选项的命令来配置。
- 已有配置,另外新增配置信息
git config --global --add user.name hanmeimei
配置 color
设置 color.ui 为 true 来打开所有的预设终端着色:
$ git config --global color.ui true
配置别名
一些常用的别名配置:
$ git config --global alias.unstage 'reset HEAD'
# 当你敲入命令:
# $ git unstage test.py
# 实际上Git执行的是:
# $ git reset HEAD test.py
$ git config --global alias.st status
$ git config --global alias.co checkout
$ git config --global alias.ci commit
$ git config --global alias.br branch
$ git config --global alias.last 'log -1'
# git last 就能显示最近一次的提交
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
--abbrev-commit是展示缩略的 commit 编号的意思
git lg 的效果,可以清晰的看提交日志:

3. 查看配置信息
批量查看
列出当前项目所有 Git 的配置(包括 system 和 global)
git config --listcredential.helper=osxkeychain user.name=hfy [email protected] alias.co=checkout alias.br=branch alias.lol=log --oneline alias.ci=commit alias.st=status alias.lg=log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit alias.last=log -1 color.ui=true core.repositoryformatversion=0 core.filemode=true core.bare=false core.logallrefupdates=true core.ignorecase=true core.precomposeunicode=true remote.origin.url=git@git.in.zhihu.com:zhihu/comment.git remote.origin.fetch=+refs/heads/*:refs/remotes/origin/* branch.master.remote=origin branch.master.merge=refs/heads/master branch.fix-activity-json.remote=origin branch.fix-activity-json.merge=refs/heads/fix-activity-json列出 global 范围的 git 配置
git config --list --globaluser.name=hfy [email protected] alias.co=checkout alias.br=branch alias.lol=log --oneline alias.ci=commit alias.st=status alias.lg=log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit alias.last=log -1 color.ui=true列出 system 范围的 git 配置
git config --list --systemcredential.helper=osxkeychain
单一配置的查看
git config user.name
git config --get user.name
4. 删除配置信息
用于只有一个值的键
git config --global --unset user.name用于一个键多个值的情况,确定删除哪一个
git config --global --unset user.name hanfangyu