【问题标题】:Bash Script: Changing file permissions recursivelyBash 脚本:递归更改文件权限
【发布时间】:2017-10-23 01:23:03
【问题描述】:

我需要一个 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

【问题讨论】:

    标签: bash recursion file-permissions


    【解决方案1】:

    您可以通过两次调用 find 命令来完成此操作,其中 -user 选项按用户过滤,-type 选项按文件类型过滤:

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

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

    【讨论】:

      【解决方案2】:

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

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

      我没有对此进行测试,它可能有点错误。我建议先测试一下:)

      【讨论】:

        【解决方案3】:

        使用find:

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

        【讨论】:

          猜你喜欢
          • 2016-08-12
          • 1970-01-01
          • 1970-01-01
          • 2013-09-17
          • 1970-01-01
          • 1970-01-01
          • 2020-05-12
          • 2019-01-11
          • 1970-01-01
          相关资源
          最近更新 更多