git添加被.gitignore忽略的文件

技术背景

在git操作中,有时候为了保障线上分支的简洁性,会在.gitignore文件中屏蔽一些关键词,比如可以加一个*.txt来屏蔽掉项目中所有带txt后缀的文件,还可以加上*test*来屏蔽所有的本地测试文件或者目录(当然,这个操作需要谨慎,有时候线上版本也需要同步测试案例)。那么如果想在被屏蔽的文件中找几个特殊案例,传到线上版本去,要如何操作呢?

操作流程

  1. .gitignore文件中添加屏蔽关键词,比如我们添加一个pdb后缀的屏蔽关键词:*.pdb
  2. 首先我们进入一个空的目录,并创建一个pdb后缀的文件:
$ ll
total 8
drwxr-xr-x 2 dechin dechin 4096 Jun 16 09:25 ./
drwxr-xr-x 7 dechin dechin 4096 Jun 16 09:25 ../
$ git status
On branch constraint
Your branch is up to date with 'origin/constraint'.

nothing to commit, working tree clean
$ touch test.pdb
$ ll
total 8
drwxr-xr-x 2 dechin dechin 4096 Jun 16 09:25 ./
drwxr-xr-x 7 dechin dechin 4096 Jun 16 09:25 ../
-rw-r--r-- 1 dechin dechin    0 Jun 16 09:25 test.pdb

此时如果我们查看再次查看git status,会跟前面一次得到一样的结果,因此我们创建的是一个pdb后缀的文件,而在.gitignore文件中已经屏蔽了所有pdb后缀的文件,因此git操作会自动忽略这个文件。

$ git status
On branch constraint
Your branch is up to date with 'origin/constraint'.

nothing to commit, working tree clean
  1. 使用git add -f强制传到线上版本。
$ git add -f test.pdb
$ git status
On branch constraint
Your branch is up to date with 'origin/constraint'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        new file:   test.pdb

可以看到此时的git状态中已经补充了对该pdb文件的更新,如果要传到线上版本,补充一步git commit -m 'xxx'git push即可。而如果我们想要取消上传的话,就需要走下面这一步操作。
4. 直接使用git reset xxx.pdb终止提交,或者也可以使用git reset HEAD <file>...来回退到某个指定的版本。

$ git reset test.pdb
$ git status
On branch constraint
Your branch is up to date with 'origin/constraint'.

nothing to commit, working tree clean
$ ll
total 8
drwxr-xr-x 2 dechin dechin 4096 Jun 16 09:25 ./
drwxr-xr-x 7 dechin dechin 4096 Jun 16 09:25 ../
-rw-r--r-- 1 dechin dechin    0 Jun 16 09:25 test.pdb

可以看到操作之后在git的状态中已经没有了这个pdb文件,但是在系统上这个文件依然存在。另外如果需要回退到指定的版本,可以先用git log来查看相关的提交信息:

$ git log --oneline -n 5
0dfd492 (HEAD -> constraint, origin/constraint) Update the
 ch3 model
d73457b Update the add hydrogen module
880a93e Update molecule file from dev
e873d8e Delete unused data
43cb306 Move the params module into forcefield

总结概要

使用.gitignore来屏蔽一些文件名的关键字是一个比较常规的操作,其目的是可以过滤掉一些只需要在本地保留而不是上传到远程仓库上面的这样一些文件。但是如果存在一些冲突,比如我们需要传到远程仓库上的文件的文件名,刚好在屏蔽的关键字清单内,此时就需要使用到本文介绍的一些操作方法,来强制上传文件。

版权声明

本文首发链接为:https://www.cnblogs.com/dechinphy/p/gitaddf.html

作者ID:DechinPhy

更多原著文章请参考:https://www.cnblogs.com/dechinphy/

打赏专用链接:https://www.cnblogs.com/dechinphy/gallery/image/379634.html

腾讯云专栏同步:https://cloud.tencent.com/developer/column/91958

CSDN同步链接:https://blog.csdn.net/baidu_37157624?spm=1008.2028.3001.5343

51CTO同步链接:https://blog.51cto.com/u_15561675

posted @ 2022-06-16 10:20  DECHIN  阅读(719)  评论(0编辑  收藏  举报