下面是 Git 常用命令及其简明示例,适合日常基于命令行的开发使用:
🧱 基础配置
bash
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
git config --global core.editor "code --wait"
git config --list # 查看全局配置
📁 仓库操作
初始化/克隆仓库
bash
git init # 初始化当前文件夹为 Git 仓库
git clone <url> # 克隆远程仓库到本地,常用的是这个,会把远程的仓库下载到当前目录下并且创建一个库名称的目录。
git clone <url> <dir> # 克隆到指定目录
## ❗ 不推荐长期使用这种方式,因为 URL 会保留在 .git/config 文件中,可能导致凭证泄漏。
git clone https://<username>:<password_or_token>@github.com/user/repo.git # 你可以将用户名和密码(或 Token)直接嵌入 URL 中
✅ 使用 Git 凭据助手(推荐做法
对于 HTTPS 方式,你也可以先配置全局凭据存储方式,让 Git 记住你的登录信息:
bash
git config --global credential.helper store # 永久保存(明文)
git config --global credential.helper cache # 临时保存(15 分钟)
git config --global credential.helper manager # 使用 Git Credential Manager(推荐)
📄 文件操作
添加文件到暂存区
bash
git add <file> # 添加单个文件
git add . # 添加所有变动(包括新文件、修改和删除)
提交更改
bash
git commit -m "描述信息" # 提交暂存区内容
git commit -am "快速提交" # 添加并提交已跟踪文件(跳过新文件)
查看状态和日志
bash
git status # 查看当前状态
git log # 查看提交历史
git log --oneline # 简洁查看历史
⬅️ 撤销与还原
bash
git restore <file> # 撤销修改(还原为最近一次提交)
git restore --staged <file> # 取消 git add 的文件
git reset --hard HEAD # 回到最近一次提交的状态
git reset --hard <commit_id> # 强制回退到某次提交
🌿 分支管理
bash
git branch # 查看本地分支
git branch <branch> # 创建新分支
git checkout <branch> # 切换分支
git checkout -b <branch> # 创建并切换到新分支
git merge <branch> # 合并某分支到当前分支
git branch -d <branch> # 删除分支
🔁 远程仓库操作
bash
git remote -v # 查看远程仓库信息
git remote add origin <url> # 添加远程仓库
git push -u origin master # 第一次推送并设置默认上游分支
git push # 推送当前分支到远程
git pull # 拉取远程最新代码并合并
git fetch # 获取远程更新但不合并
🧪 标签(Tag)
bash
git tag # 查看标签
git tag v1.0 # 创建标签
git tag -d v1.0 # 删除本地标签
git push origin v1.0 # 推送标签
git push origin --tags # 推送所有标签
🧰 其他常用命令
bash
git diff # 查看未暂存的更改
git diff --cached # 查看已暂存的更改
git stash # 暂存当前修改
git stash pop # 恢复最近一次 stash
git cherry-pick <commit> # 应用指定提交
✅ 推荐使用场景小结
任务 | 命令举例 |
---|---|
初始化仓库 | git init |
克隆项目 | git clone https://github.com/user/repo.git |
添加并提交 | git add . && git commit -m "init" |
创建新分支 | git checkout -b dev |
合并分支 | git checkout main && git merge dev |
推送远程 | git push origin main |
拉取远程 | git pull |
回退到指定提交 | git reset --hard <commit> |
查看历史记录 | git log --oneline |