常用 Git 指令
1. 基本操作
初始化 Git 仓库
将当前文件夹初始化为 Git 仓库:
bash
git init
克隆仓库
克隆远程 Git 仓库到本地:
bash
git clone <repository-url>
2. 查看仓库状态
查看当前仓库状态
查看工作区与暂存区的差异:
bash
git status
查看提交日志
查看提交历史:
bash
git log
查看某文件的修改历史
查看指定文件的提交历史:
bash
git log <file-name>
3. 文件管理
添加文件到暂存区
添加某个文件到暂存区:
bash
git add <file-name>
添加所有更改的文件:
bash
git add .
提交更改
提交暂存区的更改:
bash
git commit -m "commit message"
撤销对文件的修改
将文件恢复到最后一次提交的状态:
bash
git checkout -- <file-name>
删除文件
从工作区和 Git 仓库中删除文件:
bash
git rm <file-name>
4. 分支操作
查看分支
查看所有分支:
bash
git branch
查看远程分支:
bash
git branch -r
创建新分支
创建一个新分支并切换到该分支:
bash
git checkout -b <branch-name>
切换分支
切换到指定分支:
bash
git checkout <branch-name>
删除本地分支
删除本地分支:
bash
git branch -d <branch-name>
合并分支
将指定分支的更改合并到当前分支:
bash
git merge <branch-name>
查看分支图
查看分支图,帮助理解分支的结构:
bash
git log --oneline --graph --all
5. 远程操作
查看远程仓库
查看配置的远程仓库信息:
bash
git remote -v
拉取远程仓库的更改
拉取远程仓库并自动合并到当前分支:
bash
git pull
推送本地更改到远程仓库
推送当前分支的更改到远程仓库:
bash
git push origin <branch-name>
拉取远程分支
拉取远程仓库的指定分支:
bash
git fetch origin <branch-name>
删除远程分支
删除远程仓库的分支:
bash
git push origin --delete <branch-name>
6. 其他常用操作
查看文件差异
查看工作区与暂存区的差异:
bash
git diff
查看文件与上次提交的差异
查看文件内容与上次提交的差异:
bash
git diff <file-name>
修改最后一次提交
如果提交信息写错了,可以修改最后一次提交信息:
bash
git commit --amend
查看配置
查看当前 Git 配置:
bash
git config --list
设置 Git 配置信息
设置用户信息(如邮箱、用户名等):
bash
git config --global user.name "Your Name"
git config --global user.email "youremail@example.com"
查看邮箱用户信息(如邮箱、用户名等):
bash
git config user.name
git config user.email
清理不再需要的文件
Git 会留下许多没有跟踪的文件,使用此命令可以清理它们:
bash
git clean -f
小技巧
快捷查看某个文件的差异
你可以指定文件查看当前更改:
bash
git diff <file-name>
忽略特定文件
使用 .gitignore
文件来告诉 Git 忽略特定的文件或文件夹。例如,忽略所有 .log
文件:
*.log