git log & git status & .gitignore & git rm 从仓库中删去某个文件

本文介绍了Git中的常用命令,包括如何查看提交的文件、配置别名简化gitlog命令、查看当前状态、使用.gitignore文件排除特定文件以及如何利用git rm命令进行文件管理。通过这些实用技巧,帮助开发者更高效地使用Git进行版本控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

查看提交了哪些文件:

配置git lg/adog,方便查看git log 分支信息:

git config --global alias.adog "log --all --decorate --oneline --graph"
git config --global alias.lg "log --graph --abbrev-commit --decorate --date=relative --all"
git log --stat
git show --stat

查看当前状态:

git status  #默认输出
git status src/build  -u  # 查看某个目录中untractked的文件
git status -s # short输出

.gitignore:

  • .gitignore常用语法:

斜杠“/”表示目录, 是否以斜杠开头有很大区别,如 /buildbuild/ 的区别:其中 build/ 表示不管在哪个位置的 build 目录都会被忽略;

星号“*”通配多个字符;

问号“?”通配单个字符

方括号“[]”包含单个字符的匹配列表;

叹号“!”表示取反,即不忽略(跟踪)匹配到的文件或目录;

此外,git 对于 .ignore 配置文件是按行从上到下进行规则匹配的,意味着如果前面的规则匹配的范围更大,则后面的规则将不会生效;

  • example:

(1)规则:myfolder/*
     说明:忽略目录 myfolder 下的全部内容;不管是根目录(.gitignore文件所在的目录)下的 /myfolder/ 目录,还是某个子目录 /child/myfolder/ 目录,都会被忽略;

(2)规则:/myfolder/*
     说明:只忽略根目录下的 /myfolder/ 目录的全部内容;

# Ignore everything
*

# But not these files...
!.gitignore
!src/*
!/myfolder/file1.txt

# ...even if they are in subdirectories
!*/

说明:忽略全部内容,除了 .gitignore 文件、所有的 src 目录 和 仓库根目录下的 /myfolder/file1.txt 文件;


Use git rm:

git rm file1.txt  // 将文件从该git分支上删除(会在硬盘上消失,但是不会影响其他分支)
git rm --cached file1.txt  // 表示git不再跟踪该文件,不会在硬盘上删除(即可以再 git add 添加进来)

git commit -m "remove file1.txt"

Use --cached option to unstage and remove paths only from the index. Working tree files, whether modified or not, will be left alone.


有时候在.gitignore中新添加规则然后运行 git add . 还是会将不想要的文件添加进去,这是因为.gitignore还没有生效(因为版本控制不会因为你现在修改了.gitignore文件而将你已经添加进去的文件删除),不过可以这样(一定要先commit,不然所做的修改会丢失!):

git commit -am "commit everything first!"
git rm -r --cached .  // 这里会从git仓库中清除所有文件,而不是从硬盘上删除文件
git add .   // 这里又将所有文件添加进git仓库,同时.gitignore规则会生效
git commit -m "fixed untracked files"

This removes all files from the repository and adds them back (this time respecting the rules in your .gitignore).

Remember to commit everything you changed before you do this.

see link: http://stackoverflow.com/questions/2047465/how-can-i-delete-a-file-from-git-repo

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值