How to exclude some files from the loop in shell script [duplicate]

人走茶凉 提交于 2021-02-11 15:37:54

问题


#! /bin/sh
for file in $Files/*.txt; do
    chmod 777 $file
done

It will give permission 777 to all .txt files but I've 7 other .txt file for which I don't want to give 777 permission. How can I do that?


回答1:


you can add a conditional check as below. As there's no clear attribute differentiating the files you want to exclude, you'd need to specifically check for each name :

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



回答2:


A POSIX sh solution.

#! /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



回答3:


You can do this :

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

And it will do. Let me know if it helps!



来源:https://stackoverflow.com/questions/60303268/how-to-exclude-some-files-from-the-loop-in-shell-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!