Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for Linux file permissions (numeric notation)

I can't for the life of me figure out the proper regex for this.

What I'm looking for is a regex to match a valid numeric representation of Linux file permissions (e.g. 740 for all-read-none, 777 for all-all-all). So far I've tried the following:

strtotest=740
echo "$strtotest" | grep -q "[(0|1|2|3|4|5|7){3}]"
if [ $? -eq 0 ]; then
    echo "found it"
fi

The problem with the above is that the regex matches anything with 1-5 or 7 in it, regardless of any other characters. For example, if strtotest were to be changed to 709, the conditional would be true. I've also tried [0|1|2|3|4|5|7{3}] and [(0|1|2|3|4|5|7{3})] but those don't work as well.

Is the regex I'm using wrong, or am I missing something that has to deal with grep?

like image 402
Sho Kei Avatar asked Nov 16 '12 14:11

Sho Kei


People also ask

How read permission is represented in numeric in Linux?

Numerically, read access is represented by a value of 4, write permission is represented by a value of 2, and execute permission is represented by a value of 1. The total value between 1 and 7 represents the access mode for each group (user, group, and other).

What does 755 permissions look like?

755 - owner can read/write/execute, group/others can read/execute. 644 - owner can read/write, group/others can read only. Some directory permission examples: 777 - all can read/write/search.

What does chmod 644 mean?

Permissions of 644 mean that the owner of the file has read and write access, while the group members and other users on the system only have read access.

Why is chmod 777?

The command chmod -R 777 / makes every single file on the system under / (root) have rwxrwxrwx permissions. This is equivalent to allowing ALL users read/write/execute permissions. If other directories such as home, media, etc are under root then those will be affected as well.


2 Answers

what you want is probably

grep -Eq "[0-7]{3}"

edit: if you're using this for finding files with certain permissions, you should rather have a look at find (-perm) or stat

like image 159
mata Avatar answered Oct 01 '22 07:10

mata


The simplest and most obvious regexp which is going to work for you is:

grep -q '(0|1|2|3|4|5|7)(0|1|2|3|4|5|7)(0|1|2|3|4|5|7)'

Here is an optimized version:

grep -Eq '(0|1|2|3|4|5|7){3}'

since 6 can represent permissions as well, we could optimize it further:

grep -Eq '[0-7]{3}'
like image 20
Oleksandr Kravchuk Avatar answered Oct 01 '22 08:10

Oleksandr Kravchuk