git alias和命令行

git alias

以下命令放在.gitconfig 的[alias]下(提示:git config -e --global 可以直接打开.gitconfig)

更加简洁和漂亮的 git log

lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit -n 20

格式化的 git message,带 github moji

feat = "!f() { git commit -m \":sparkles: feat($1): $2\"; }; f"
fix = "!f() { git commit -m \":bug: fix($1): $2\"; }; f"
chore = "!f() { git commit -m \"chore($1): $2\"; }; f"
style = "!f() { git commit -m \":art: style($1): $2\"; }; f"
docs = "!f() { git commit -m \":memo: docs($1): $2\"; }; f"
refactor = "!f() { git commit -m \":recycle: refactor($1): $2\"; }; f"

使用方法举例,命令行输入:git feat upload 添加上传功能
结果为 ✨ feat(upload): 添加上传功能

撤销一个 commit

undo = reset HEAD~1 --soft

根据自己需要也可以改成--mixed, --hard(慎用,一般你不会使用到),三者区别在于:

  • --soft: uncommit changes, changes are left staged (index).
  • --mixed (default): uncommit + unstage changes, changes are left in working tree.
  • --hard: uncommit + unstage + delete changes, nothing left.

简单说,假设当前你有一些工作区的改动和 staged 的文件,然后对 staged 的文件进行了 commit。这时如果选用--mixed,则之前 staged 的文件也会返回到工作区里;而使用--soft,则只是把你 commit 的东西返回到 staged 区域。

直接修改任意 commit 的 message,省略--interactive 过程

reword = "!f() { SHA=$(git rev-parse --short $1); GIT_SEQUENCE_EDITOR=\"sed -i 's/^pick ${SHA}/reword ${SHA}/'\" git rebase --interactive $SHA^; unset GIT_SEQUENCE_EDITOR;}; f"

使用方法举例,命令行输入:git reword COMMITID,回车后会弹出编辑器,修改 message 后保存退出,就完成了 rebase。

查询历史信息

git show diff 不显示“+-”号

git show --color-words

说明:用颜色代替加减号,
场景:想在终端里直接复制语句

查询关键词在哪些 commit 里出现(是 commit 的文件内容,不是 commit message)

git grep "keyword" $(git rev-list --all)

更高阶的技巧见
比如限制搜索的文件夹 3.查询关键词在哪些 commit message 里出现

git log --all --grep "fixme"

分支操作

删除某个分支

git branch -d localBranch // 删除本地分支,如果没有该分支没有被merge,要加上-D
git push origin --delete remoteBranch // 删除远程分支

删除某个 tag

git tag -d localTag // 删除本地分支,如果没有该分支没有被merge,要加上-D
git push origin --delete remoteTag // 删除远程分支

列出远程分支(跳过本地缓存)

git ls-remote --heads origin

如果远程分支删除了把本地的也删除了

git fetch --prune

不切换分支的情况下更新另外一个分支

git fetch origin test:test
# 或者
git fetch origin test
git branch -f test origin/test # 但是要注意这样会强制更新

文件操作

恢复某个被删除的文件

git checkout commit_id -- file_name

这里 commit_id 是你最后一次还有这个文件的时候的 commit,如果觉得麻烦,你可以先找到哪次 commit 删除了这个文件,然后使用 commit_id^表示紧邻着的上一个 commit。

posted @ 2025-04-06 23:50  Atten  阅读(52)  评论(0)    收藏  举报