Git常用操作

Git学习教程

自学git时所使用的git教程,如果是初学 Git,那么学完第7章就差不多了。

Git操作三板斧

git status

1
git status

用于查看当前分支的基本信息,如“处于什么分支”“有哪些文件被修改”“有哪些文件未被追踪”等。

git add

1
2
git add .
git add <file>

这条命令用于把修改存入暂存区,如果只想暂存特定的几个文件,就写对应的文件名。

git commit

1
git commit -m"简略的信息"

这条命令用于提交暂存区的修改,引号内可以简略写上本次提交所做的修改内容。

安装与一次性配置

1
2
3
git --version                       # 验证是否安装成功
git config --global user.name "Your Name"
git config --global user.email "you@example.com"

分支与合并

1
2
3
4
5
6
7
8
git branch                          # 列出本地分支
git branch <name> # 新建分支
git switch -c <name> # 新建并立即切换
git switch <name> # 切换已有分支
git merge <branch> # 合并分支
git rebase <branch> # 线性化历史
git branch -d <name> # 删除已合并分支
git branch -D <name> # 强制删除

远程协同

1
2
3
4
5
6
7
git remote -v                       # 查看远程
git remote add origin <url> # 关联远程仓库
git push -u origin main # 首次推送
git push # 以后直接 push
git pull # 拉取并合并
git fetch # 仅拉取
git push origin --delete <branch> # 删除远程分支

撤销与回退

1
2
3
4
5
6
git restore <file>                  # 撤销工作区修改
git restore --staged <file> # 撤销暂存
git commit --amend # 修改最后一次提交
git reset --hard <commit> # 回退并丢弃改动
git reset --soft/--mixed <commit> # 回退但保留改动
git revert <commit> # 生成反向提交(公共历史安全)