I'm trying to create a bash script that will be able to perform a find command to get the permissions and full path of every file/directory in a directory tree and create a file for each unique permission and printing each full file path to that permissions file. Then in the future I could read these files and use them to permissions to the way they were when I ran the script.

For instance:

drwxrwxrwx /home/user/testDirectory  
-rwxrwxrwx /home/user/testDirectory/testFile  
drwxr-xr-x /home/user/testDirectory/directory2  
-rwxr-xr-x /home/user/testDirectory/directory2/test2 

The above would create 2 files (e.g. 777.txt and 755.txt) that would each have 2 of the lines.

I am struggling with the logic to create a file for each unique permission and then send the full file path.

What I have so far (I doubt the array is necessary, but I have played with sorting the array by permission which I can do with -k 1.2 on the sort command to ignore the d flag):

declare -a PERMS


while read line
     (( i++ ))
done < <( find /opt/sas94 -printf ""%M/" "%p/"\n")
  • Can we assume that none of your directory or file names will contain a newline character? – roaima Jun 6 at 18:56
  • Since directory and file names can easily contain one or more spaces I'd suggest you put the permissions number/string as the first item and the path name as the remainder of the line. – roaima Jun 6 at 18:59
  • Yes no newline characters. The permissions are the first thing printed by the find command. Looking at my initial post I realize the format screwed up for the example output of the file command. But each line starts with a permission and then the full path. One combo per line. – Varathiel Jun 6 at 19:06
  • What is going on with your quotes “-printf ""%M/" "%p/"\n"”? – ctrl-alt-delor Jun 6 at 19:13
  • Apparently, the ones around the %M and %p are unnecessary. It works both as ""%M/" "%p/"\n" and "%M/ %p/\n". – Varathiel Jun 6 at 19:29

Try this:


while read file; do
        stat -c '%A %n' "$file" >> $(stat -c '%a' "$file").txt
done < <(find "$1")


./script.sh /path/to/directory
  • the first stat -c '%A %n' "$file" prints the permissions and path to the file, e.g. -rw-rw-rw- /foo/bar
  • the second stat -c '%a' "$file" prints the permissions in octal form, e.g. 666

The output of the first stat is appended to the filename created by the second stat with suffix .txt.

  • Thank you! This works great. – Varathiel Jun 7 at 15:01

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.