6

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! :-)

0

2 Answers 2

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###"
4

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .