【问题标题】:How to modify bash command to change permissions如何修改 bash 命令以更改权限
【发布时间】:2013-08-19 15:45:46
【问题描述】:

我有这个 bash 命令来修改根文件夹内的所有文件和文件夹权限:

find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;

它工作正常。 我应该做些什么来排除一些文件夹以更改根文件夹(执行bash的地方)内的权限。 例如,如果我想保留文件夹“A”和文件夹“B”的文件夹权限 提前致谢

【问题讨论】:

  • 你能举一个目录布局的例子吗?之前和之后?
  • 当然。例如,我有一个“Products”文件夹和一些文件夹:“ProductA”、“ProductB”、“ProductC”等。当我运行脚本时,所有文件夹都得到 755。但我希望能够排除“ProductA”和“ProductC”更改权限
  • 所以只需要修改根目录下目录的权限吗?

标签: linux bash permissions


【解决方案1】:

使用-prune 选项排除目录:

find . -type d -name ProductA -prune -o -type d -exec chmod 755 {} \;

它告诉:如果文件是目录并且名称为ProductA,则不要进入它(-prune),否则(-o 表示或)如果文件是目录,则执行chmod 755就可以了。

find 表达式由选项、测试(可以为假或真)和操作组成,由运算符分隔。如果未给出任何操作,则对表达式为真的所有文件执行-print 操作。 -exec 是一个动作,-prune 是另一个动作。您可以使用-a-o 链接多个操作。 expr1 -a expr2 将执行这两个操作,而 expr1 -o expr2 将仅在 expr1 评估为 false 时执行 expr2

所以如果要排除多个目录,可以这样写

find . -type d -name ProductA -prune -o -type d -name ProductC -prune -o -type d -exec chmod 755 {} \;
find . -type d -name ProductA -prune -o -type d -name ProductC -prune -o -type f -exec chmod 644 {} \;

或者只是:

find . -type d -name "Product[AC]" -prune -o -type d -exec chmod 755 {} \;
find . -type d -name "Product[AC]" -prune -o -type f -exec chmod 644 {} \;

你也可以将它们组合起来:

find . -type d -name "Product[AC]" -prune -o -type d -exec chmod 755 {} \; -o -type f -exec chmod 644 {} \;

如果你有一个更复杂的目录结构,比如说你想排除ProductA/data而不是ProductB/data或者ProductA/images,那么你可以使用-path测试:

find . -path ./ProductA/src -prune -o -print

【讨论】:

  • 很好,谢谢,但是如果我想忽略排除文件夹中的所有文件,我该怎么办。例如,假设我想排除“ProductA”和“ProductC”文件夹,但也忽略它们的所有文件。
  • 我说的是第二行: find 。 -type f -exec chmod 644 {} \;
  • 使用这个命令:find . -type d -name ProductA -prune -o -type f -exec chmod 644 {} \;。它将递归地遍历文件和目录。如果找到名为ProductA 的目录,则将从搜索中修剪,这意味着将排除属于ProductA 目录的所有文件。因此,您将仅更改对其他文件的权限。您可以通过要求find 使用find . -type d -name ProductA -prune -o -type f -print 打印找到的文件来检查它们
【解决方案2】:

你可以试试这个:

find . -type d \(-name "*" ! -name "A" ! -name "B" \) -exec chmod 755 {}\;

find . -type d \(-name "*" - 列出当前目录下的所有目录

!-name "A" !-name "B" - 忽略名称为 A 和 B 的目录

【讨论】:

    【解决方案3】:

    您可以排除多个目录,例如dirname1, dirname2 使用 egrep -v 然后执行 chmod 使用 xargs

    find . -type d | egrep -v "(dirname1|dirname2)" | xargs chmod 755
    

    【讨论】:

      猜你喜欢
      • 2018-01-06
      • 2020-08-12
      • 2011-08-24
      • 1970-01-01
      • 2012-11-20
      • 2016-09-03
      • 2011-06-17
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多