Bash 脚本:递归更改文件权限



我需要一个 Bash 脚本来更改目录中所有文件和所有子目录中的文件权限。它的行为应该是这样的:

for each file in directory (and subdirectories)
   if i am the owner of the file
      if it is a directory
         chmod 770 file
      else
         chmod 660 file

我想这不是一项艰巨的任务,但我在 Bash 脚本方面不是很有经验。感谢您的帮助!:D

您可以通过两次调用 find 命令来做到这一点,-user 选项用于按用户过滤,-type 选项用于按文件类型过滤:

find . -user "$USER" -type d -exec echo chmod 770 {} +
find . -user "$USER" -not -type d -exec echo chmod 660 {} +

测试后删除echo,以实际更改权限。

find在这里很有用:它递归地查找满足特定条件的文件和/或目录(在本例中为所有者(。另一个技巧是使用X(而不是x(标志来chmod,这使得目录是可执行的,但不是常规文件。通过xargs将其放在一起:

find . -user $(whoami) | xargs chmod ug=Xo=

我没有测试这个,它可能有点错误。我建议先测试它:)

使用 find

find topdirectory -user "$USER" ( -type f -exec chmod 660 {} + ) -o ( -type f -exec chmod 770 {} + )

最新更新