Git 常用的alias命令大全

内容分享2个月前发布
0 0 0

Git 常用的alias命令大全

Git 的 alias(别名)功能可以将常用的复杂命令简化,大幅提升操作效率。以下是一些实用的 Git alias 配置和常用示例:

一、配置 alias 的方法

通过 git config 命令设置,分为:

  • 当前仓库有效(配置写入 .git/config):
  • bash
  • git config alias.别名 ‘原始命令’
  • 全局有效(所有仓库通用,配置写入 ~/.gitconfig):
  • bash
  • git config –global alias.别名 ‘原始命令’

二、常用 alias 推荐

1. 基础操作简化

bash

git config --global alias.st status         # 状态查看(git st)
git config --global alias.co checkout       # 切换分支/恢复文件(git co)
git config --global alias.br branch         # 分支管理(git br)
git config --global alias.cm commit         # 提交(git cm)
git config --global alias.cma 'commit --amend'  # 修正上次提交(git cma)
git config --global alias.cl clone          # 克隆仓库(git cl)
git config --global alias.pull 'pull --rebase'  # 拉取并变基(避免无谓合并)

2. 日志查看增强

bash

# 简洁日志(单行显示)
git config --global alias.lg 'log --oneline --graph --decorate'

# 详细日志(显示修改内容摘要)
git config --global alias.lgg 'log --graph --pretty=format:"%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset" --abbrev-commit'

# 显示最近 n 条日志(例如 git l 5 查看最近5条)
git config --global alias.l 'log -n'

3. 分支与合并

bash

git config --global alias.rb rebase         # 变基(git rb)
git config --global alias.mg merge          # 合并(git mg)
git config --global alias.brd 'branch -d'   # 删除分支(git brd)
git config --global alias.brD 'branch -D'   # 强制删除分支(git brD)
git config --global alias.brr 'branch -vv'  # 查看分支关联远程情况

4. 撤销与回滚

bash

git config --global alias.unstage 'reset HEAD --'  # 撤销暂存(git unstage 文件)
git config --global alias.restore 'checkout --'    # 恢复工作区文件(git restore 文件)
git config --global alias.rst 'reset --hard'       # 硬重置(git rst HEAD~1 回滚上次提交)
git config --global alias.cleanup 'clean -fd'      # 清理未跟踪文件和目录

5. 远程仓库操作

bash

git config --global alias.pu push           # 推送(git pu)
git config --global alias.puall 'push --all'  # 推送所有分支
git config --global alias.track 'branch --set-upstream-to=origin/'  # 关联远程分支(git track 分支名)
git config --global alias.remote-update 'remote update'  # 更新远程分支信息

三、直接编辑配置文件(更高效)

如果需要批量配置,可以直接编辑 ~/.gitconfig(全局)或 .git/config(本地),添加如下内容:

[alias]
    st = status
    co = checkout
    br = branch
    cm = commit
    lg = log --oneline --graph --decorate
    lgg = log --graph --pretty=format:"%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset" --abbrev-commit
    unstage = reset HEAD --
    restore = checkout --
    # 更多别名...

四、使用技巧

  • 别名可以嵌套,例如 git config –global alias.lg1 ‘lg -10’(查看最近 10 条简洁日志)
  • 忘记别名时,用 git help -a 查看所有可用命令(包括别名)

根据自己的使用习惯配置 alias,能显著减少重复输入,提升 Git 操作体验!

© 版权声明

相关文章

暂无评论

none
暂无评论...