【问题标题】:How to exclude some files from the loop in shell script [duplicate]如何从shell脚本中的循环中排除一些文件[重复]
【发布时间】:2020-02-19 15:05:25
【问题描述】:
#! /bin/sh
for file in $Files/*.txt; do
    chmod 777 $file
done

它将向所有 .txt 文件授予 777 权限,但我还有 7 个其他 .txt 文件我不想授予 777 权限。我怎样才能做到这一点?

【问题讨论】:

  • 好吧,您需要一些 属性 来区分它们,以便区分需要任一组权限的那些。我们不知道你必须在你的问题中解释这一点。
  • 我在 $FILE 目录中总共有 50 个 .txt 文件。现在我想为除这 7 个 .txt 文件之外的所有文件授予 777 权限:school.txt college.txt abra.txt cab.txt jamla.txt kalut.txt aura.txt
  • 知道了。请看我的回答
  • 无论您希望完成什么,chmod 777 都是错误危险的。您将希望恢复到尽快获得合理的权限(对于您的用例,可能是chmod 755),如果您在面向公众的系统上有全球可写系统文件,至少要调查它是否可能被破坏并用作闯入的支点您组织的网络。

标签: linux bash shell unix scripting


【解决方案1】:

一个 POSIX sh 解决方案。

#! /bin/sh

for file in $Files/*.txt; do
   case $file in
    foo.txt|bar.txt|more.txt) continue;;   ##: Skip files that matched.
    *) chmod 777 "$file";;                 ##: Change permission to the rest.
   esac                
done

【讨论】:

    【解决方案2】:

    您可以添加如下条件检查。由于没有明确的属性来区分您要排除的文件,因此您需要专门检查每个名称:

    for file in $Files/*.txt
    do 
        if [ "$file" = abra.txt -o "$file" = aura.txt -o "$file" = cab.txt -o "$file" = college.txt -o "$file" = jamla.txt -o "$file" = kalut.txt -o "$file" = school.txt  ]
        then 
           continue 
        fi 
        chmod 777 "$file"
    done
    

    【讨论】:

      【解决方案3】:

      你可以这样做:

      find . ! -iregex '.*/school\.txt\|.*/college.txt\|.*/abra\.txt\|.*/cab\.txt\|.*/jamla\.txt\|.*/kalut\.txt\|.*/aura\.txt' -exec chmod 777 {} \;
      

      它会做的。如果有帮助,请告诉我!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-02
        • 2021-02-08
        • 2015-01-08
        • 2015-04-10
        • 2021-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多