0%

不常用的一些Git命令

删除本地有但在远程库中已经不存在的跟踪分支(Remove tracking branches that are no longer exist on remote)

在使用基于 Pull Request 模式的开发流程中,一般我们都会设置为PR通过后自动删除对应的Branch。长此以往,本地的Repo中就会残留很多老旧(Stale)无用的Tracking Branch。

1
git remote prune origin

prune 这个词的本意是修剪树枝、修剪羽毛,Git Repo的多分支特性可以看成是一个复杂的多叉树,因此这个命令很形象的表达了这个意思。

忽略跟踪本地Repo的某些文件(Ignore watching/tracking a particular directory/file)

有时候我们想在本地Repo中做一些特定的修改(例如配置文件、数据库连接信息等),但又不能、不想提交到代码库中,我们可以告诉Git暂时忽略某些文件。

1
git update-index --assume-unchanged path-to-file

这样Git就会忽略对该文件的修改。如果想恢复对该文件的修改跟踪,执行下面的命令即可。

1
git update-index --no-assume-unchanged path-to-file

如果需要经常使用这两个命令,可以给它们创建别名:

1
2
git config --global alias.hide 'update-index --assume-unchanged'
git config --global alias.unhide 'update-index --no-assume-unchanged'

下次使用的时候:

1
2
3
git hide path-to-file
or
git unhide path-to-file

这个命令和.gitignore文件的作用是不一样的。.gitignore文件用于指示Git将指定的文件或文件夹完全排除在Git的管理之外,所有其它用户的Repo都将遵循.gitignore文件中定义的规则。上述两个命令只对当前本地的Repo产生作用,不影响其它用户的Repo。

修改最后一个commit的author(Change the author of the latest commit)

Git有全局的配置可以设置Git Repo的用户名及邮箱。但是某些Git Repo你可能想使用一个不同的用户名及邮箱,例如工作邮箱或者个人邮箱。很多在线的Git Repo还提供基于邮箱地址的Gravatar头像服务。因此你可能发现在提交某个Commit之后,用户名及邮箱弄错了。

1
2
3
git config --local user.name "FirstName LastName"
git config --local user.email "first.last@example.com"
git commit --amend --reset-author --no-edit

或者

1
git commit --amend --author="Author Name <email@address.com>" --no-edit

修改远程Repo的地址(Changing a remote’s URL)

1
git remote set-url origin https://github.com/USERNAME/REPOSITORY.git