5

I'm attempting to create a bash script where I check if all the files of a specific folder (/tmp) have the permission 755. I also need it to delete all the files that don't have permission value 755.

I've attempted this so far with no luck:

#!/bin/bash
for filename in 'ls' 
do 
if [ -perm 0755 "$filename" ] 
then echo "Files with 755 permission: $filename" 
else rm "$filename" 
fi 
done 
echo "###DONE###"

Any help you can provide will be greatly appreciated! :-)

  • 2
    find /tmp -not -perm 755 -delete should work. Warning: try find /tmp -not -perm 755 first to check whether the expected files are listed. – Jos Apr 26 '16 at 10:49
  • Note that your script doesn't list, nor delete, hidden files. The find command will. – Jos Apr 26 '16 at 10:51
  • @Jos post that as an answer before someone else does :) – Sergiy Kolodyazhnyy Apr 26 '16 at 14:00
6

The following script should do what you want: it runs in the directory youre calling it:

#!/bin/bash
echo "###START###"
for filename in * 
do 
    if [ $(stat -c "%a" "$filename") == "755" ] 
    then 
        echo "Files with 755 permission: $filename" 
    else 
        echo "REMOVING: $filename"
        rm "$filename" 
    fi 
done 
echo "###DONE###"
| improve this answer | |
2

Your script could simply consist of:

#!/bin/bash
echo "Files with 755 permission:"
find . -perm 755
echo "Deleting all other files"
find . -not -perm 755 -delete
echo "Done"

Note that it will delete files from the current directory and all directories beneath it. It will also delete anything with a permission other than 755 without warning, so use carefully.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.