将权限重置为默认值

lll*_*ook 15 chmod

如何根据掩码将权限重置为默认值,以便他们将权限设置为刚刚创建的文件

我想要实现的示例: umask设置为 0022 所以

touch file
mkdir directory
Run Code Online (Sandbox Code Playgroud)

文件的权限现在是 rw-r--r--

目录的权限现在是 rwxr-xr-x

chmod 777 file
chmod 777 directory
Run Code Online (Sandbox Code Playgroud)

文件的权限现在是 rwxrwxrwx

目录的权限现在是 rwxrwxrwx

有没有办法将 perms 重置为默认值,以便文件rw-r--r--和目录rwxr-xr-x使用chmod

mur*_*uru 15

使用减法仅适用于某些 umask 值 - 最好使用,例如在 PSkocik 的答案中,或(或对于目录)应用标准指定的 umask,如 ilkkachu 在评论中所述mode & ~umaskchmod =rwchmod =rwx


在某些情况下,您只需减去文件和目录的umaskfrom即可获得默认权限:06660777

$ printf "%04d\n" "$((0777 - $(umask)))"
0755
$ printf "%04d\n" "$((0666 - $(umask)))"
0644
Run Code Online (Sandbox Code Playgroud)

因此,您可以申请chmod

chmod $((0666 - $(umask))) file
chmod $((0777 - $(umask))) directory
Run Code Online (Sandbox Code Playgroud)

在 bash 中,您必须使用printf以八进制强制输出:

$ printf "%04d\n" "$((0777 - $(umask)))"
0493
$ printf "%04o\n" "$((0777 - $(umask)))"
0755
Run Code Online (Sandbox Code Playgroud)

另一种方法是创建一个新文件和目录,并将它们用作参考:

touch file2
mkdir directory2 
chmod --reference=directory2 directory
chmod --reference=file2 file
Run Code Online (Sandbox Code Playgroud)

  • 我还发现了类似`chmod =rwx file`的东西,不确定它到底做了什么,但看起来它也将权限重置为默认值,但仅限于目录 (3认同)
  • `chmod =rwx file` 也有效,它将权限设置为由 umask 修改的 0777。请参阅 https://pubs.opengroup.org/onlinepubs/9699919799.2018edition/utilities/chmod.html 中带有“if *who* is not specified”的句子 (2认同)

PSk*_*cik 8

掩码是通过掩码按位AND应用的,bitwise negated因此如果您想创建自己的最终权限模式,您可以执行以下操作:

$((mode & ~umask))
Run Code Online (Sandbox Code Playgroud)

您需要将其打印回八进制,以便您可以将其传递给chmod

$ chmod `printf '%o' $((0777 & ~$(umask)))` directory
$ chmod `printf '%o' $((0777 & ~0111 & ~$(umask)))` file
#^additional implicit mask of 0111 for files
Run Code Online (Sandbox Code Playgroud)

其中 0777 是您要应用掩码的权限模式(您可以使用stat -c %a file或获得它stat -c %a directory)。

您可以回显上述内容以查看进程替换将评估的结果(对于umaskof 0022,您将获得755and 644)。

您可以从中创建一个通用函数:

#takes a umask as first param and applies it to each folowing param (files)
maskMode(){
  local mask="$1" dmask mode a
  dmask="$((mask & ~0111))"; shift
  for a; do
    mode=0`stat -c "%a" "$a"`
    chmod `printf "%0.4o\n" $(($mode & ~mask))` "$a"
  done
}
Run Code Online (Sandbox Code Playgroud)

对于您的特定用途,chmod 参考文件是另一种选择。