本地仓库

初始化仓库

1
git init

查看文件状态

1
git status

添加文件到暂存区

1
2
git add <file>        # 添加单个文件
git add . # 添加当前目录所有更改

提交更改

1
git commit -m "描述本次更改"

查看提交历史

1
2
git log
git log --oneline # 简洁格式

撤销修改

未使用 git add

1
2
3
4
5
# 单个文件
git checkout -- filename

# 所有文件
git checkout .

已使用 git add, 未使用 git commit

1
2
3
4
5
# 单个文件
git reset HEAD filename

# 所有文件
git reset HEAD

已使用 git commit

1
2
3
4
5
6
7
8
9
# 回退到上一次 commit 的状态
git reset --hard HEAD^

# 回退到任意版本
git reset --hard [commit_id]

# 回退到原来版本
git reflog
git reset --hard [commit_id]

远程仓库

克隆远程仓库

1
git clone https://github.com/username/repo.git

添加远程仓库地址

1
git remote add origin https://github.com/username/repo.git

推送到远程仓库

  • 首次推送
1
git push -u origin main
  • 之后
1
git push

拉取远程更新

1
git pull

分支操作

查看分支

1
2
3
4
5
# 查看所有分支
git branch -a

# 查看远程分支
git branch -r

创建并切换分支

1
git checkout -b new-branch-name

切换分支

1
2
3
git checkout branch-name
# 或
git switch branch-name

合并分支

  • 将 feature 合并到 main
1
2
git checkout main
git merge feature

删除分支

1
git branch -d branch-name

其它

查看差异

1
git diff