Skip to content

Git / GitHub CLI

安装

bash
brew install git gh
powershell
winget install --id Git.Git -e --source winget
winget install --id GitHub.cli -e --source winget
bash
apt update
apt install -y git gh

Windows 中 WinGet 不可用时,可分别从 Git for WindowsGitHub CLI 下载安装。

安装完成后重启终端并检查版本:

bash
git --version
gh --version

Git for Windows 安装选项

  • Add a Git Bash Profile to Windows Terminal:将 Git Bash 添加到 Windows Terminal。
  • Windows Explorer integration:如果已经集成到 Windows Terminal,可不添加 Git Bash 和 Git GUI 右键菜单。

Git 配置

配置文件路径为 ~/.gitconfig

初始配置

bash
git config --global user.name "<name>"
git config --global user.email "<email>"
git config --global init.defaultBranch main

查看配置

bash
# 查看全部全局配置
git config --global --list

# 查看指定配置
git config --global user.name

常用配置

bash
# 区分文件名大小写
git config --global core.ignoreCase false

# 忽略文件权限变化
git config --global core.filemode false

# 统一使用 LF 换行
git config --global core.autocrlf false
git config --global core.eol lf

GitHub CLI

登录 GitHub:

bash
gh auth login

按交互提示选择 GitHub.com、HTTPS 和使用浏览器登录。登录后将 Git 凭据交由 GitHub CLI 管理:

bash
gh auth setup-git

检查登录状态:

bash
gh auth status

HTTP 代理

Shell 环境变量

Git 进程会继承 Shell 环境变量。可在 ~/.bashrc 等 Shell 配置文件中设置:

bash
export HTTP_PROXY="http://127.0.0.1:7897"
export HTTPS_PROXY="http://127.0.0.1:7897"
export NO_PROXY="localhost,127.0.0.1,::1"

Git 配置

bash
# 设置代理
git config --global http.proxy http://127.0.0.1:7897
git config --global https.proxy http://127.0.0.1:7897

# 取消代理
git config --global --unset http.proxy
git config --global --unset https.proxy

SSH

配置 SSH Key

生成 SSH Key:

bash
ssh-keygen -t ed25519 -C "key_name"

# 兼容不支持 Ed25519 的旧环境
# ssh-keygen -t rsa -b 4096 -C "key_name"

常用参数:

  • -t:指定密钥类型。
  • -C:添加注释。
  • -f:指定密钥文件的保存路径和名称。

执行后会在 ~/.ssh 中生成私钥和公钥:

bash
├── id_ed25519
└── id_ed25519.pub

将公钥添加到 GitHub 的 Settings → SSH and GPG keys → New SSH key,然后测试连接:

bash
ssh -T git@github.com

使用 SSH 地址克隆仓库:

bash
git clone git@github.com:example/repo.git

SSH 代理(Ubuntu)

安装 Corkscrew:

bash
apt update
apt install -y corkscrew

编辑 ~/.ssh/config

bash
Host github.com
  HostName ssh.github.com
  Port 443
  User git
  IdentityFile ~/.ssh/id_ed25519
  IdentitiesOnly yes
  ProxyCommand corkscrew 127.0.0.1 7897 %h %p

配置多个 SSH Key

生成不同用途的密钥:

bash
ssh-keygen -t ed25519 -C "personal" -f ~/.ssh/id_ed25519_personal
ssh-keygen -t ed25519 -C "work" -f ~/.ssh/id_ed25519_work

配置 ~/.ssh/config

bash
Host github.com
  HostName ssh.github.com
  Port 443
  User git
  IdentityFile ~/.ssh/id_ed25519_personal
  IdentitiesOnly yes

Host codeup.aliyun.com
  HostName codeup.aliyun.com
  Port 22
  User git
  IdentityFile ~/.ssh/id_ed25519_work
  IdentitiesOnly yes

不同仓库可单独配置用户名和邮箱:

bash
git config user.name "your-name"
git config user.email "your-email@example.com"

也可以通过条件配置自动切换账号:

ini
[user]
  name = example
  email = example@mail.com

[includeIf "gitdir:~/work/**"]
  path = ~/.gitconfig-work
ini
[user]
  name = work-name
  email = work@example.com

基于 MIT 许可发布