3. git config

文章目录

  • 基本概述
  • 配置级别
  • 基本用法
    • 设置配置项
    • 查看配置项
    • 删除配置项
  • 常用配置项

基本概述

git config 的作用是:设置用户信息、编辑器、别名、仓库行为等。

配置级别

级别 作用范围 配置文件路径 命令选项
仓库级别(Local) 当前仓库 .git/config 无(默认选项)
全局级别(Global) 当前用户
所有仓库
~/.gitconfig(Linux/macOS)
用户\xxx.gitconfig% (Windows)
- -global
系统级别(System) 所有用户
所有仓库
/etc/gitconfig(Linux/macOS)
Git安装目录\etc\gitconfig(Windows)
- -system
  • 优先级从高到低为:系统 > 全局 > 仓库

基本用法

设置配置项

1.格式

git config [级别] [选项] <key> <value>

2.例子

# 设置用户名和邮箱(全局)
git config --global user.name "Your Name"
git config --global user.email "[email protected]"

查看配置项

1.查看所有配置项

# 查看所有配置项(含来源文件)
git config --list --show-origin

2.查看指定配置项

git config --get user.name

3.直接打开文件查看

$ cat .git/config
[core]
        repositoryformatversion = 0
        filemode = false
        bare = false
        logallrefupdates = true
        symlinks = false
        ignorecase = true
        editor = code --wait
[gui]
        wmstate = normal
        geometry = 1205x669+152+152 276 304
[remote "origin"]
        url = [email protected]:xxx1231/xxx.git
        fetch = +refs/heads/*:refs/remotes/origin/*
[branch "local_branch"]
        remote = origin
        merge = refs/heads/local_branch
[init]
        defaultBranch = main

删除配置项

1.删除全局级别的配置

git config --global --unset user.email

2.删除所有级别的配置(慎用)

git config --unset-all user.name

常用配置项

1.用户信息

git config --global user.name "Your Name"
git config --global user.email "[email protected]"
  • 必须配置名字和邮箱才能进行 commit 操作

2.默认文本编辑器

# 设置 VSCode 为默认编辑器
git config --global core.editor "code --wait"

# 其他编辑器示例:
# Vim: git config --global core.editor "vim"
# Nano: git config --global core.editor "nano"

3.设置默认分支名称

git config --global init.defaultBranch main
  • 将默认分支从 “master” 改为 “main”

4. 凭证存储(避免重复输入密码)

# 使用缓存(默认15分钟)
git config --global credential.helper cache

# 自定义缓存时间(例如1小时)
git config --global credential.helper "cache --timeout=3600"

# 永久存储(慎用)
git config --global credential.helper store  # 明文保存到 ~/.git-credentials

5.配置别名(Alias)

# 简化常用命令
git config --global alias.st "status"
git config --global alias.br "branch"
git config --global alias.ci "commit"
git config --global alias.co "checkout"
  • 配置别名后,输入 git st ,就相当于输入了 git status

你可能感兴趣的:(Git,git)