如何对组的linux上的文件的权限与所有者相同?

时间:2015-11-30 13:39:08

标签: linux bash shell file file-permissions

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

e.g。 之前:

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'

1 个答案:

答案 0 :(得分:4)

使用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

如果您想要在评论和更新的问题中指明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)