1

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
i=0
while read line
do
 PERMS[$i]="$line"
 (( i++ ))
done < <( find /opt/sas94 -printf ""%M/" "%p/"\n")
Rui F Ribeiro
57.9k28 gold badges154 silver badges237 bronze badges
asked Jun 6, 2019 at 18:41
5
  • Can we assume that none of your directory or file names will contain a newline character? Commented Jun 6, 2019 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. Commented Jun 6, 2019 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. Commented Jun 6, 2019 at 19:06
  • What is going on with your quotes "-printf ""%M/" "%p/"\n""? Commented Jun 6, 2019 at 19:13
  • Apparently, the ones around the %M and %p are unnecessary. It works both as ""%M/" "%p/"\n" and "%M/ %p/\n". Commented Jun 6, 2019 at 19:29

1 Answer 1

3

Try this:

#!/bin/bash
while read file; do
 stat -c '%A %n' "$file" >> $(stat -c '%a' "$file").txt
done < <(find "1ドル")

Usage:

./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.

answered Jun 6, 2019 at 20:28
1
  • Thank you! This works great. Commented Jun 7, 2019 at 15:01

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.