复制文件权限的标准方法

Ale*_*lex 10 unix command-line chmod posix

我试图找到一种标准的 POSIX 方式来将一个文件的权限复制到另一个文件。在 GNU 系统上,这很容易:

[alexmchale@bullfrog ~]$ ls -l hardcopy.*
-rw-r--r-- 1 alexmchale users 2972 Jul  8 20:40 hardcopy.1
---------- 1 alexmchale users 2824 May 14 13:45 hardcopy.4
[alexmchale@bullfrog ~]$ chmod --reference=hardcopy.1 hardcopy.4
[alexmchale@bullfrog ~]$ ls -l hardcopy.*
-rw-r--r-- 1 alexmchale users 2972 Jul  8 20:40 hardcopy.1
-rw-r--r-- 1 alexmchale users 2824 May 14 13:45 hardcopy.4
Run Code Online (Sandbox Code Playgroud)

不幸的是,chmod 的 --reference 标志是一个非标准选项。所以这是出于我的目的。我更喜欢它是单线的,但这不是必需的。最终,它确实需要采用 POSIX sh 语法。

Stu*_*der 13

您可以使用该stat命令获取文件权限:

  • Mac OS X (BSD) 语法:

    chmod `stat -f %A fileWithPerm` fileToSetPerm

  • Linux 语法(不确定):

    chmod `stat -c %a fileWithPerm` fileToSetPerm

`符号是反引号。


Den*_*son 7

一种诱惑是解析ls. 避免这种诱惑

以下似乎有效,但它充满了克鲁格。它依赖于cp保留目标文件的权限。对于此演示,文件“模板”必须不存在。

  • 将具有您想要的权限的文件复制到文件
  • 将要更改的文件复制到上一步创建的文件中
  • 删除要更改的原始文件
  • 将中间文件重命名为要更改的文件名

演示:

$ echo "contents of has">has
$ echo "contents of wants">wants
$ chmod ug+x has     # just so it's different - represents the desired permissions
$ cp has template
$ cat has
contents of has
$ cat wants
contents of wants
$ cat template
contents of has
$ ls -l has wants template
-rwxr-xr-- 1 user user 16 2010-07-31 09:22 has
-rwxr-xr-- 1 user user 16 2010-07-31 09:23 template
-rw-r--r-- 1 user user 18 2010-07-31 09:22 wants
$ cp wants template
$ ls -l has wants template
-rwxr-xr-- 1 user user 16 2010-07-31 09:22 has
-rwxr-xr-- 1 user user 18 2010-07-31 09:24 template
-rw-r--r-- 1 user user 18 2010-07-31 09:22 wants
$ cat template
contents of wants
$ rm wants
$ mv template wants
$ ls -l has wants
-rwxr-xr-- 1 user user 16 2010-07-31 09:22 has
-rwxr-xr-- 1 user user 18 2010-07-31 09:24 wants
$ cat has
contents of has
$ cat wants
contents of wants
Run Code Online (Sandbox Code Playgroud)