【问题标题】:How to make the permission of files on linux of group same to owner?如何使组linux上文件的权限与所有者相同?
【发布时间】:2016-03-04 04:04:20
【问题描述】:

如何递归更改文件/目录的权限,使其成为与所有者权限相同的组权限?

例如 之前:

640 x.txt
744 y
400 y/z.txt

之后:

660 x.txt
774 y
440 y/z.txt

感谢 fedorqui 将其创建为答案:

find . -name '*' -print0 | xargs -0 bash -c 'for file; do 
perm=$(stat -c '%a' "$file")
new_perm=$(sed -r "s/^(.)./\1\1/" <<< "$perm")
chmod "$new_perm" "$file";
done'

【问题讨论】:

  • 如果您始终希望保持用户和组权限相同,一个有用的开始是更改您的 umask:umask 002

标签: linux bash shell file file-permissions


【解决方案1】:

使用stat可以获得文件的权限。

例如:

$ touch a
$ stat -c '%a' a
644

然后,如果我们捕获到这个值,我们可以使用sed 使第二个字段与第一个字段具有相同的值:

$ sed -r "s/^(.)./\1\1/" <<< "644"
664

然后我们准备说

chmod 664 file

现在我们已经有了所有的部分,看看我们如何将它们粘合在一起。这个想法是捕获stat 输出的第一个字符以生成新值:

perm=$(stat -c '%a' file)
new_perm=$(sed -r "s/^(.)./\1\1/" <<< "$perm")
chmod "$new_perm" file

然后,就是遍历文件并执行以下操作:

for file in pattern/*; do
   perm=$(stat -c '%a' "$file")
   new_perm=$(sed -r "s/^(.)./\1\1/" <<< "$perm")
   chmod "$new_perm" "$file"
 done

如果您希望在 cmets 和更新后的问题中显示 find 结果,则可以使用 process substitution

while IFS= read -r file; do
   perm=$(stat -c '%a' "$file")
   new_perm=$(sed -r "s/^(.)./\1\1/" <<< "$perm")
   chmod "$new_perm" "$file";
done < <(find . -name '*' -print0)

【讨论】:

  • 谢谢,唯一缺少的是递归性 :-)
  • @wdk 有一个漂亮的for 循环,如果你处于两个级别,它可以做到这一点。否则,如果这包含更多级别,您可以通过进程替换使用find
  • @wdk 更新为 find 方法,因为您在更新的问题中使用它的方式有点矫枉过正。
猜你喜欢
  • 2018-09-01
  • 2011-04-13
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
  • 1970-01-01
  • 2011-12-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多