查看全局配置
1 2 3 4 5 6 7 8
| git config --global user.name "你的用户名"
git config --global user.email "你的邮箱地址"
git config --list
|
配置 SSH 密钥连接 GitHub
使用 SSH 连接可以免去每次推送代码时输入密码的麻烦。
生成本地 SSH 密钥对:
1
| ssh-keygen -t ed25519 -C "your_email@example.com"
|
按三下回车(保持默认路径、不设置密钥密码)即可生成。
查看并复制公钥内容:
1 2 3 4 5
| cat ~/.ssh/id_ed25519.pub
cat ~/.ssh/id_ed25519.pub
|
复制输出的全部内容(以 ssh-ed25519 开头,你的邮箱结尾)。
将公钥添加到 GitHub:
- 登录 GitHub -> 点击右上角头像 -> Settings。
- 左侧菜单选择 SSH and GPG keys。
- 点击右上角 New SSH key。
- Title 随意填写(如 “Macbook Pro”),Key 粘贴刚刚复制的内容,点击 Add SSH key。
测试 SSH 连接是否成功:
如果提示 Are you sure you want to continue connecting (yes/no/[fingerprint])?,输入 yes 并回车。看到 Hi [你的用户名]! You've successfully authenticated... 即表示连接成功。
创建与初始化仓库
克隆现有的远程仓库
1 2 3 4 5
| git clone 远程仓库的SSH地址
git clone 远程仓库的HTTPS地址
|
本地项目文件夹关联远程仓库
1 2 3 4 5 6 7 8 9 10 11
| git init
git remote add origin 远程仓库的SSH地址
git remote -v
git remote set-url origin 新的仓库地址(SSH)
|
origin 是远程仓库地址(例如: git@github.com:username/my-awesome-project.git)的一个“代号”或“别名”
日常开发:暂存与提交
查看当前仓库状态
添加到暂存区 (Staging Area)
1 2 3 4 5
| git add filename.py
git add .
|
提交到本地仓库 (Repository)
1 2 3 4 5 6 7 8 9 10 11
| git commit -m "填写本次修改的日志信息(如:修复登录Bug)"
git commit -am "修改日志"
git push -u origin 分支名
git push
|
拉取与更新 (Pull / Fetch)
1 2 3 4 5 6 7 8
| git fetch origin
git pull origin 分支名
git pull
|
查看提交日志
1 2 3 4 5 6 7 8
| git log
git log --oneline
git log --oneline --graph --all
|
分支管理 (Branching)
分支是 Git 的核心利器,支持多人协同开发而互不干扰。
查看分支
1 2 3 4 5 6 7 8
| git branch
git branch -a
git branch -vv
|
新建分支
1 2 3 4 5
| git branch 新分支名
git switch -c 新分支名
|
建立分支关系
1 2 3 4 5
| git switch dev
git push -u origin dev
|
切换分支
合并分支 (Merge)
1 2 3 4 5
| git switch main
git merge 被合并的分支名
|
删除分支
1 2 3 4 5 6 7 8
| git branch -d 分支名
git branch -D 分支名
git push origin --delete 远程分支名
|
撤销与版本回滚
注意:涉及 --hard 的回滚操作会抹除未提交的工作,请务必谨慎使用。
撤销工作区的修改(未执行 git add)
1 2
| git restore filename.py
|
撤销暂存区的修改(已执行 git add,但未 git commit)
1 2
| git restore --staged filename.py
|
修改最后一次提交(未推送到远程)
1 2
| git commit --amend -m "新的正确提交信息"
|
版本回退 (Reset)
1 2 3 4 5 6 7 8
| git reset --soft 提交的CommitID
git reset --hard 提交的CommitID
git reset --hard HEAD^
|