Linux umask 命令使用详解

新建一个文件或目录,它的默认权限是什么?如果要修改一个用户创建的文件和目录的默认权限该如何做?本文将介绍相关的内容。说明:本文演示的Linux环境为 Ubuntu 16.04。

文件的默认权限

为了查看用户创建的文件和目录的默认权限,我们用一个普通的用户创建文件 myfile 和目录 mydir 并查看它们的默认权限:

Linux umask 命令使用详解

目录的权限为 775,文件的权限为 664。对比之下发现目录比文件多了执行的权限。这是因为执行权限对于目录来说是非常重要的,有了目录的执行权限才能够进入目录中进行文件操作。
默认情况下对于目录来说最大的权限是 777,对于文件来说最大的权限一般为 666(只有可以执行的文件才添加可执行权限)。所以我们创建的文件和目录的共同特点是从最大权限中减去了 2,也就是其他用户的写权限。而这个被减去的值就是我们常说的 umaskumask 还是 bash 的一个内置命令,默认输出当前用户的 umask 值:

注意,umask 显示的值为从默认的最大权限中减去的值。上图中的第一个 0 表示的是特殊权限位,这里我们可以暂时忽略它。

系统的默认策略(Ubuntu16.04)
系统在用户登录时通过 login 程序调用 pam_umask 模块设置用户默认的 umask。从 login 程序的配置文件 /etc/login.defs 中我们可以找到 umask 相关的配置:

# UMASK is the default umask value for pam_umask and is used by
# useradd and newusers to set the mode of the new home directories.
# 022 is the "historical" value in Debian for UMASK
# 027, or even 077, could be considered better for privacy
# There is no One True Answer here : each sysadmin must make up his/her
# mind.
#
# If USERGROUPS_ENAB is set to "yes", that will modify this UMASK default value
# for private user groups, i. e. the uid is the same as gid, and username is
# the same as the primary group name: for these, the user permissions will be
# used as group permissions, e. g. 022 will become 002.
#
# Prefix these values with "0" to get octal, "0x" to get hexadecimal.
#
UMASK          022
……..
# Enable setting of the umask group bits to be the same as owner bits
# (examples: 022 -> 002, 077 -> 007) for non-root users, if the uid is
# the same as gid, and username is the same as the primary group name.
#
# If set to yes, userdel will remove the user´s group if it contains no
# more members, and useradd will create by default a group with the name
# of the user.
#
USERGROUPS_ENAB yes

乍一看上面的配置信息,用户的默认 umask 应该是 022 才对啊。仔细地阅读相关的说明信息发现,当 USERGROUPS_ENAB 被设置为 yes 时(默认值),对于 uid 和 gid 相同且用户名和主组名相同的用户,系统会把其 umask 改为 002。所以我们看到用户 nick 的 umask 为 002。
由于 root 用户的特殊性,它默认的 umask 与其它用户是不同的,其值为 022:

umask 命令

umask 是 bash 的一个内置命令,用来显示或设置新建文件/目录的权限掩码(umask)。前面我们以数字的方式输出了用户默认的 umask 值,这次我们以符号的方式进行输出:

$ umask -S

以符号输出的就是用户创建目录时的默认权限,算一下,其实就是 775。

为了改变用户创建的文件/目录的默认值,我们可以改变 umask 的默认值。
设置 umask 值
最简单的方式就是为 umask 命令指定一个数字:

$ umask 026

026 的含义为:去掉 group 中的写权限,去掉 other 中的读写权限。

Linux umask 命令使用详解

这时创建的文件权限为 640,目录权限为 751。注意,修改 umask 后只有新建的文件和目录受影响,已经存在的文件和目录的权限不会被影响。

以符号的方式设置 umask 值
比如下面的命令:

$ umask u=, g=w, o=rwx

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/12458.html