chmod 是否按指定顺序修改 FILE... 参数的权限?

Does chmod modify permissions of FILE... arguments in the order specified?

给定一个带有多个 FILE 参数的 chmod 调用,

$ chmod 0xxx FILE-1 FILE-2 FILE-3 ...

是否有可预测的处理顺序?当 FILE-kFILE-j 相关时,这可能很重要,例如当一个是另一个的子目录时。比如说,FILE-1 是某个目录 d1FILE-2 子目录 d1/d2,即第二个参数命名第一个参数的子目录:

$ chmod 0000 d1 d1/d2
chmod: cannot access `d1/d2': Permission denied

O.K.,这是我所期望的,即从左到右阅读反映了处理FILE...参数的顺序,d1的权限首先被清除并且,因此,chmod 并不意味着获得对 d1/d2 的访问权限。因此,以下调用也按预期工作:

$ chmod 0000 d1/d2 d1

这会清除任一目录的权限。但是这种顺序依赖性是否得到保证,更一般地说,POSIX 是否对此事有所说明?关于跨 Unix 系统的可预测性,选项 -R 是否会以某种方式影响推理?

虽然未指定,但所有实现的行为都自然,就像您所经历的那样,但不能保证,请注意POSIX(IEEE Std 1003.1-2008 , 2016 Edition) 在 chmod 命令手册中说 - A​​pplication Usage:

Some implementations of the chmod utility change the mode of a directory before the files in the directory when performing a recursive (-R option) change; others change the directory mode after the files in the directory. If an application tries to remove read or search permission for a file hierarchy, the removal attempt fails if the directory is changed first; on the other hand, trying to re-enable permissions to a restricted hierarchy fails if directories are changed last. Users should not try to make a hierarchy inaccessible to themselves.

因此可以应用参数的任何顺序,您需要使用单独的命令来确保顺序。

似乎没有在任何地方指定。

但是,Manual Page for CHMOD 的“应用程序使用”部分确实指定了命令的递归行为。

经过多次实验,我在 x86_64 GNU/Linux 运行 Ubuntu 14.04.5 LTS 上获得了与您相同的结果。

它似乎从左到右计算权限,当它无法更改权限时停止。

  • 如果你想撤销权限,那么最好把父目录放在最后。 (即在文件层次结构中从叶到根)

  • 如果你想授予权限,那么最好先有父目录。 (即文件层次结构中的根到叶)