Git 常用命令

Git 常用命令

参考书籍:

1 添加远程服务器,使本地仓库连接到 remote 端

git remote add origin <server>

2 将本地 HEAD 中的改动推送到远端仓库

git push -u origin <branch> # 第一次提交时需要加 -u,建立本地分支与远端分支的跟踪关系 git push origin <branch> # 之后普通推送

3 创建新分支并切换过去

git checkout -b feature_x

4 切换回主分支

git checkout master

5 删除分支

git branch -d feature_x

6 用远程仓库 origin 的 branch 分支更新本地的当前分支

git pull [origin [branch]]

相当于 git fetch + git merge。如果只想拉取某远程分支而不合并,用 git fetch。

7 查看不同分支之间的差异

git diff <source_branch> <target_branch>

8 为提交的指定 ID 版本打上标签

# 打附注标签(推荐) git tag -a version_number -m "说明信息" <commit-id> # 打轻量标签 git tag version_number <commit-id>

9 丢弃本地修改

# 丢弃单个文件的本地修改 git checkout -- <filename> # 丢弃本地所有修改(谨慎使用!建议先用 git stash 保存) git reset --hard

git reset --hard 会丢失工作区和暂存区中的所有未提交改动且不可恢复,务必先确认。 如果只是想临时保存改动,用 git stash push / git stash pop。

10 彩色的 git 输出

git config color.ui true

11 显示历史记录时每个提交的信息只显示一行

git config format.pretty oneline

12 使用 HTTPS 协议时免密码 clone

通过 credential helper 将凭据缓存在内存中,timeout 指定缓存的过期时间(秒),可按需调大:

git config --global credential.helper "cache --timeout=31536000" # 缓存一年 # 如需永久保存(明文写入 ~/.git-credentials),用: git config --global credential.helper store

13 设置 Vim 为默认编辑器

git config --global core.editor "vim"

14 拉取远程的指定分支到本地

git fetch origin <remote-branch>:<local-branch> # 例:git fetch origin docker-deploy:docker-deploy

15 支持中文显示

echo "export LESSCHARSET=utf-8" >> ~/.bashrc

16 给服务添加版本号

echo $(date +%Y.%m.%d)-$(git rev-list HEAD --count)-$(git rev-parse --short HEAD)

其中 git rev-parse --short HEAD 输出当前 commit 的简短形式(即 commitid 前 7 个字符):

git rev-parse --short HEAD

17 查看变更文件列表

git log --stat

18 将更新的文件拷贝到指定目录

拷贝当前有变更(已修改/未跟踪)的文件到目标目录,适合发布脚本之类的场景:

res=$(git status -s) for file in $res do if [ -f "$file" -a "$file" != "git_cp.sh" ]; then cp "$file" "/build/front/lua/$file" fi done

git status -s(short)输出的每行由两个字符的状态码 + 文件名组成,逐行遍历即可拿到变更文件清单。

19 查看当前分支名

git rev-parse --abbrev-ref HEAD

20 常用组合命令

git status -s # 精简查看工作区状态 git log --oneline -10 # 最近 10 条提交,每行一条 git log -p -- <file> # 查看某个文件的每次提交差异
阅读 — · 全站 —
🎸 我的歌单 0 首