背景
最近在做有关shell编程的技术分享,了解到这个命令。
问题引入
不多说,上手就行:
gerrylon@gl:~$ ls a.txt
ls: cannot access 'a.txt': No such file or directory
gerrylon@gl:~$ touch a.txt
gerrylon@gl:~$ lsattr a.txt
--------------e---- a.txt
gerrylon@gl:~$
上面我新创建了一个文件a.txt, 然后用lsattr
来查看,发现有个e
的标志,这个在man chattr
中发现这么一句话:
The ‘e’ attribute indicates that the file is using extents for mapping the blocks on disk. It may not be removed using chattr(1).
大概是说映射磁盘上的块,不能通过chattr
命令来删除。
不懂这个是什么意思,欢迎会的同学来评论区说下。
实验
还有其他一些标识,列举如下:
-
a
只能append(也就是>>
) -
i
不能修改 -
A
文件的atime
将不会变
更多的可以自行学习。
针对上面给的几个来证实下:
a标志
gerrylon@gl:~$ lsattr a.txt
--------------e---- a.txt
gerrylon@gl:~$ chattr +a a.txt
chattr: Operation not permitted while setting flags on a.txt
gerrylon@gl:~$ sudo chattr +a a.txt
gerrylon@gl:~$ lsattr a.txt
-----a--------e---- a.txt
gerrylon@gl:~$ echo hello > a.txt # 设置了追加标志a,所以不能覆盖
bash: a.txt: Operation not permitted
gerrylon@gl:~$ echo hello >> a.txt # 只能追加
gerrylon@gl:~$
i标志
再来测试下i
:
gerrylon@gl:~$ lsattr a.txt
-----a--------e---- a.txt
gerrylon@gl:~$ sudo chattr =i a.txt # 通过=i这种方式,可以直接设置i属性,原来的属性都会被重置
gerrylon@gl:~$ lsattr a.txt # 可以看到现在只有i标志了
----i-------------- a.txt
gerrylon@gl:~$ echo aa > a.txt
bash: a.txt: Operation not permitted
gerrylon@gl:~$ echo bb >> a.txt
bash: a.txt: Operation not permitted
gerrylon@gl:~$ vim a.txt
gerrylon@gl:~$ cat a.txt
hello
通过上述例子可以看到,加了i
标志的文件,不能改,不能追加。
A标志
gerrylon@gl:~$ lsattr a.txt # 首先我们看看,目前只有i标志
----i-------------- a.txt
gerrylon@gl:~$ stat a.txt # 看下文件的atime(Access)
File: a.txt
Size: 6 Blocks: 8 IO Block: 4096 regular file
Device: 10307h/66311d Inode: 6835754 Links: 1
Access: (0744/-rwxr--r--) Uid: ( 1000/gerrylon) Gid: ( 1000/gerrylon)
Access: 2020-05-31 15:23:52.585364669 +0800
Modify: 2020-05-31 15:21:10.848547377 +0800
Change: 2020-05-31 15:38:26.142308423 +0800
Birth: -
gerrylon@gl:~$ cat a.txt # 试图改变atime
hello
gerrylon@gl:~$ stat a.txt # 发现atime变了
File: a.txt
Size: 6 Blocks: 8 IO Block: 4096 regular file
Device: 10307h/66311d Inode: 6835754 Links: 1
Access: (0744/-rwxr--r--) Uid: ( 1000/gerrylon) Gid: ( 1000/gerrylon)
Access: 2020-05-31 15:38:41.082439949 +0800
Modify: 2020-05-31 15:21:10.848547377 +0800
Change: 2020-05-31 15:38:26.142308423 +0800
Birth: -
gerrylon@gl:~$ sudo chattr -i +A a.txt # 现在让文件仅保留A标志
gerrylon@gl:~$ lsattr a.txt
-------A----------- a.txt
gerrylon@gl:~$ cat a.txt # 再次尝试改变atime
hello
gerrylon@gl:~$ stat a.txt # 发现atime没有变
File: a.txt
Size: 6 Blocks: 8 IO Block: 4096 regular file
Device: 10307h/66311d Inode: 6835754 Links: 1
Access: (0744/-rwxr--r--) Uid: ( 1000/gerrylon) Gid: ( 1000/gerrylon)
Access: 2020-05-31 15:38:41.082439949 +0800
Modify: 2020-05-31 15:21:10.848547377 +0800
Change: 2020-05-31 15:39:02.718791113 +0800
Birth: -
gerrylon@gl:~$
通过上面的例子可以看了,文件加了A
标志后, 其atime(正常情况下,文件内容被读取时会变)就不变了。如果你的文件频繁读取的话,这样可以有效节约磁盘IO,这也可以作为系统的一个优化点。
总结
活到老,学到老。
欢迎补充指正!