我为什么批评 Git(以及你为什么也应该批评它)
如今,很多人使用像oh-my-zsh这样的工具,它们自带大量实用功能,包括 Git 快捷键。别误会我的意思——它们确实很棒。但我认为了解底层工作原理至关重要。你可以随意使用各种工具,但从头开始构建自己的工作流程才是真正有价值的。
如果你好奇我为什么应该编写自己的工具,可以在这里查看我的想法。但现在,我想向你展示Bash 函数和别名如何让 Git 工作流程更快、更轻松、更高效。我希望这篇文章能让你兴奋地深入研究 shell 的 rc 文件,并开始编写自己的自定义函数和别名,不仅适用于 Git,也适用于你所做的一切!
1. Git 别名
首先,让我们简化一些常用的 Git 命令。以下是我设置的一些别名,可以让你在终端中操作更轻松一些。既然可以将其缩短为两个字母,为什么每次都要输入一个长命令呢?
alias gs="git status" # Show Git status
alias ga="git add ." # Add all files to the staging area
alias gc="git commit -m" # Commit with a message
alias gp="git push" # Push the current branch to the remote
alias gl="git pull" # Pull from the remote branch
alias glog="git log --oneline --graph --all --decorate" # View Git log in one-line format
alias gco="git checkout" # Checkout a branch
alias gcb="git checkout -b" # Create and switch to a new branch
alias gd="git diff --cached" # View the difference of staged changes
alias grh="git reset --hard HEAD" # Hard reset to the latest commit
alias gb="git branch -vv" # Show branches and last commit in one-line format
alias gf="git fetch --all" # Fetch all remote branches
这些别名确实能节省几秒钟,但这些时间加起来就多了。而且,它们用起来感觉还不错。
2.用于更复杂的 Git 工作流程的 Bash 函数
现在,让我们通过一些自定义Bash 函数来更上一层楼,这些函数可以让你的工作更加自动化。这些函数可以让你免于输入多个命令,并确保你不会错过任何步骤。
2.1.创建新分支并推送
gnew() {
git checkout -b "$1"
git push -u origin "$1"
}
# Usage: gnew branch_name
2.2.快速提交和推送
gquick() {
got add .
git commit -m "$1"
git push
}
# Usage: gquick "commit message"
2.3.将当前分支变基到主分支
grebase() {
git fetch
git rebase origin/main
}
# Usage: grebase
2.4.撤消上次提交
gundo() {
git reset --soft HEAD~1
}
# Usage: gundo
2.5.压缩提交
gsquash() {
git reset --soft HEAD~"$1"
git commit --amend
}
# Usage: gsquash 3 (to squash the last 3 commits)
2.6.与上游同步 Fork
gupdate-fork() {
git fetch upstream
git checkout main
git merge upstream/main
git push origin main
}
# Usage: gupdate-fork
2.7.基于先前提交的交互式 Rebase
grebasei() {
git rebase -i HEAD~"$1"
}
# Usage: grebasei 3 (to interactively rebase the last 3 commits)
3.通用工作流程增强器
这些最终功能增强了常规 Git 工作流程,使工作更加高效。
3.1.显示 Git 树
glogtree() {
git log --graph --oneline --decorate --all
}
# Usage: glogtree
3.2.重置分支到远程
gresetremote() {
git fetch origin
git reset --hard origin/"$(git rev-parse --abbrev-ref HEAD)"
}
# Usage: gresetremote
4.为你的或添加别名和函数.bashrc
.zshrc
如果你希望这些函数和别名在终端会话之间保持不变,则需要将它们添加到你的.bashrc
或 中.zshrc
。操作方法如下:
-
打开你的 shell 配置文件:
nvim ~/.bashrc # OR ~/.zshrc
-
将别名和函数粘贴到文件中。
-
保存后,刷新你的shell:
source ~/.bashrc # OR ~/.zshrc
这些只是一些让 Git 为你工作,而不是被 Git 干扰的方法。只需花几分钟调整一下你的 shell 设置,就能节省你几个小时的打字和点击时间。那么你呢?
文章来源:https://dev.to/jimmymcbride/why-i-bash-git-and-why-you-should-too-3752