Git 常用命令
1. config
1.1. 优先级
local(默认) > system > global
1.2. 查看配置
1.3. 设置用户&邮箱
1.4. 设置代理
指定域名使用代理(例:https://github.com)
使用的 ssh 协议?
修改 ~/.ssh/config 文件Host github.com
ProxyCommand nc -X 5 -x 127.0.0.1:1080 %h %p # SOCKS5 代理
2. init
cd /path/to/my/codebase
git init
默认分支名?main 还是 master?
master 历史遗留问题,为了兼容旧版本,Git 2.23 版本引入了 main 作为默认分支名。
git config --global init.defaultBranch <main or master>
3. clone
仓库的历史记录很久,如何放弃一些历史记录?
4. status
简化输出 --shortgit status -s
5. add
添加文件到暂存区git add "<pathspec>"
<pathspec>
是什么?
<pathspec>
是 Git 命令中的一个参数,用于指定要操作的文件或目录。它可以是一个文件路径、一个目录路径、一个通配符等。
示例git add 'README.md' # 添加 README.md 文件
git add 'src/' # 添加 src 目录下的所有文件
git add '*.txt' # 添加所有以 .txt 结尾的文件,包括空格和特殊字符
git add '**/*.txt' # 添加所有以.txt 结尾的文件,包括子目录
git add '*.{txt,md}' # 添加所有以.txt 或.md 结尾的文件
git add 'src/*.{js,ts}' # 添加 src 目录下的所有以.js 或.ts 结尾的文件
git add 'src/**/*.{js,ts}' # 添加 src 目录下的所有以.js 或.ts 结尾的文件,包括子目录
git add 'src/**/*' # 添加 src 目录下的所有文件,包括子目录
如何撤销 add 操作?
git reset HEAD "<pathspec>"
git reset HEAD "." # 撤销所有文件
6. commit
提交暂存区的文件git commit -m "<commit-message>"
提交所有已跟踪文件git commit -a -m "<commit-message>"
修改上一次提交git commit --amend -m "<commit-message>"
如何撤销 commit 操作?
示例git reset HEAD~1 # 撤销上一次提交
git reset HEAD~2 # 撤销上两次提交
git reset HEAD~<n> # 撤销前 n 次提交
git reset <commit-hash> # 撤销指定提交
7. diff
比较暂存区和上次提交的差异git diff --staged
比较指定提交和当前目录的差异git diff "<commit-hash>"
比较两个提交之间的差异git diff "<commit-hash>" "<commit-hash>"
比较当前分支和指定分支的差异git diff "<branch-name>"
比较指定分支和指定提交之间的差异git diff "<branch-name>" "<commit-hash>"
显示差异的文件名git diff --name-only
显示差异的文件名和状态git diff --name-status
显示指定提交和当前目录的差异的文件名和状态git diff --name-status "<commit-hash>"
如何查看指定文件的差异?
示例git diff "README.md" # 比较 README.md 文件的差异
git diff "src/index.js" # 比较 src/index.js 文件的差异
8. branch
删除指定分支git branch -d "<branch-name>"
重命名指定分支git branch -m "<old-branch-name>" "<new-branch-name>"
9. checkout
切换到指定分支git checkout "<branch-name>"
创建并切换到指定分支git checkout -b "<branch-name>"
恢复指定文件git checkout -- "<file-path>"
10. merge
合并指定分支到当前分支git merge "<branch-name>"
合并指定分支到指定分支git merge "<branch-name>" "<branch-name>"
合并指定分支到当前分支,并创建合并提交git merge --no-ff "<branch-name>"
11. tag
创建指定标签git tag "<tag-name>"
创建指定标签并添加注释git tag -a "<tag-name>" -m "<tag-message>"
删除指定标签git tag -d "<tag-name>"
12. log
显示指定数量的提交日志git log -n "<number>"
显示指定提交日志git log "<commit-hash>"
显示指定提交日志的详细信息git log -p "<commit-hash>"
13. fetch
从远程仓库获取指定分支git fetch "<remote-name>" "<branch-name>"
从远程仓库获取所有标签git fetch --tags
从远程仓库获取指定标签git fetch --tags "<tag-name>"
从远程仓库获取所有分支和标签git fetch --all
14. pull
拉取远程仓库中与当前分支关联的远程分支git pull
从远程仓库获取指定分支并合并到当前分支git pull "<remote-name>" "<branch-name>"
15. push
将本地分支推送到远程仓库的指定分支git push "<remote-name>" "<branch-name>"
16. remote
添加远程仓库git remote add "<remote-name>" "<remote-url>"
删除远程仓库git remote remove "<remote-name>"
重命名远程仓库git remote rename "<old-remote-name>" "<new-remote-name>"
设置远程仓库的 URLgit remote set-url "<remote-name>" "<new-remote-url>"