Easy to use git

Git 本地环境部署一般分两种:

  1. 本机安装 Git,用于本地版本控制并连接 GitHub/GitLab/Gitee
  2. 在本机/局域网搭建 Git 服务器,如 Gitea、GitLab

下面先给常用本机环境部署,再给可选的本地 Git 服务部署。


1. 安装 Git

Windows

下载安装:https://git-scm.com/download/win
安装时建议勾选:

  • Add Git to PATH
  • Git Bash Here
  • 使用 OpenSSH

安装后打开 Git Bash 验证:

git --version

macOS

brew install git
# 或
xcode-select --install

Linux

# Ubuntu/Debian
sudo apt update
sudo apt install git -y

# CentOS/RHEL
sudo yum install git -y

# Fedora
sudo dnf install git -y

验证:

git --version

2. 基础配置

git config --global user.name "你的名字"
git config --global user.email "你的邮箱"
git config --global init.defaultBranch main
git config --global core.editor "vim"

Windows 建议:

git config --global core.autocrlf true

macOS/Linux 建议:

git config --global core.autocrlf input

查看配置:

git config --list

3. 配置 SSH Key,连接远程仓库

生成 SSH Key:

ssh-keygen -t ed25519 -C "你的邮箱"

一路回车即可,默认生成在:

~/.ssh/id_ed25519
~/.ssh/id_ed25519.pub

启动 ssh-agent 并添加:

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

查看公钥:

cat ~/.ssh/id_ed25519.pub

复制输出内容,添加到 GitHub / GitLab / Gitee 的 SSH Keys 设置中。

测试:


4. 创建本地 Git 仓库

mkdir myproject
cd myproject

git init

echo "# myproject" > README.md

git add .
git commit -m "init"
git branch -M main

关联远程仓库:

git remote add origin [email protected]:用户名/仓库名.git
git push -u origin main

常用命令:

git status
git log --oneline
git diff
git checkout -b dev
git pull
git push

5. 可选:本地部署 Git 服务器 Gitea

如果只是自己本机使用,git init 就够了。
如果想让局域网内多台电脑共用 Git 仓库,推荐轻量方案 Gitea + Docker

新建 docker-compose.yml

services:
  gitea:
    image: gitea/gitea:latest
    container_name: gitea
    restart: always
    environment:
      - USER_UID=1000
      - USER_GID=1000
    volumes:
      - ./gitea:/data
      - /etc/timezone:/etc/timezone:ro
      - /etc/localtime:/etc/localtime:ro
    ports:
      - "3000:3000"
      - "222:22"

启动:

docker compose up -d

访问:

http://localhost:3000

初始化时建议:

  • 数据库:SQLite3
  • SSH 服务端口:222
  • Gitea 基础 URL:http://localhost:3000/

创建仓库后,本地关联:

git remote add origin ssh://git@localhost:222/用户名/仓库名.git
git push -u origin main

局域网其他电脑访问时,把 localhost 换成服务器 IP,例如:

ssh://[email protected]:222/用户名/仓库名.git

6. 常见问题

Git 代理

git config --global http.proxy http://127.0.0.1:7890
git config --global https.proxy http://127.0.0.1:7890

取消代理:

git config --global --unset http.proxy
git config --global --unset https.proxy

多个 SSH 账号

编辑:

~/.ssh/config

示例:

Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_github

Host gitee.com
  HostName gitee.com
  User git
  IdentityFile ~/.ssh/id_ed25519_gitee

如果你告诉我你的操作系统,以及目标是“本机开发使用”还是“局域网搭建 Git 服务器”,我可以给你一份对应的一键部署命令。