给初学者的 5 个 git 技巧

2025-06-10

给初学者的 5 个 git 技巧

提高效率和整洁树的实用命令

1. 快捷方式(又名别名)

你会发现很多别名的创意,我发现最常用的是这些。你可以nano ~/.gitconfig在 Mac/Linux 系统中编辑它们。
所以,不用输入,git checkout <branch>你可以输入git co <branch>

[alias]
   co = checkout
   br = branch
   st = status
   # create a new branch from current branch and check it out
   cob = checkout -b
   # stage all changes and commit (add a message)
   a = !git add -A && git commit -m
   unstage = reset HEAD --
   last = log -1 HEAD
   hist = log --pretty=format:'%h %ad | %s%d [%an]' --graph --date=short
   # Meld the currently unstaged changes into the last commit
   fixup = !git add -A && git commit --amend --no-edit
Enter fullscreen mode Exit fullscreen mode

我将在整篇文章中使用这些。

3. Bug 和功能分支

从你的主分支或开发分支git cob bug/123创建一个用于处理问题 #123 的分支。如果你想区分 bug、任务和功能,可以使用bug/123issue/123。由于使用了正斜杠,因此在使用 git gui 工具时,它们会被组织到文件夹中。

4. 将你的 git 编辑器更改为 nano

除非您出生于 20 世纪 80 年代,否则您可能讨厌 vi 或 vim 编辑器,您可以使用以下命令进行更改:

git config --global core.editor "nano"
Enter fullscreen mode Exit fullscreen mode

使用Ctrl+o保存(即 o 表示输出)、Ctrl+x退出、Ctrl+w搜索

5. 清理你的提交

假设你创建了一个名为 bug 的分支,bug/123你可能会有大量的wip提交,例如正在进行的工作。如果你想在发布分支之前将它们全部压缩为 1 个提交,那么你可以这样git rebase -i

图片描述

图片描述

# Open interactive rebase with the last 6 commits
git rebase -i HEAD~6 
Enter fullscreen mode Exit fullscreen mode

这将打开 nano 或 vi,并能够告诉 git 要做什么:
图片描述

我们想要将所有提交压缩到一起。
最上面的提交是最旧的提交,所以你需要压缩pick它,因为它squash会与一个提交一起压缩。如果你不想将它们全部压缩到该提交上(也许你想以下一个或前一个提交作为起点,只需退出并将 HEAD 更改为 HEAD~5 或 ~7 即可。注意:务必注释掉所有带有 的行,#这样 rebase 就不会执行任何操作!

图片描述

然后保存(Ctrl+o在 nano 或<Esc> :wqvim 中)。然后它会让你选择该 rebase 的提交消息,只需注释掉(#)所有提交消息,然后输入你自己的提交消息,或者选择最合适的一个。

提示:如果您已经发布了正在处理的分支(以及所有那些嘈杂的提交),那么在本地进行 rebase 操作不会在远程更改它。因此,请先删除远程分支git push origin --delete bug/123(假设您使用origin远程分支的名称),然后在 rebase 操作后再发布它,否则下次 rebase 操作时,git pull它会将这些提交拉回到您的本地分支。

🤗感谢阅读。欢迎反馈和建议!

鏂囩珷鏉ユ簮锛�https://dev.to/omills/5-git-tips-for-beginners-453
PREV
使用 TensorFlow.js (ReactJS) 在浏览器中运行机器学习模型
NEXT
适用于您的开源 React 组件 AWS Security LIVE 的最小 CSS-in-JS 解决方案!