Sho Kei
Sho Kei

Reputation: 175

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?

Upvotes: 8

Views: 3281

Answers (4)

Oleksandr Kravchuk
Oleksandr Kravchuk

Reputation: 6319

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}'

Upvotes: 6

doubleDown
doubleDown

Reputation: 8398

Just for reference, you can do it with shell pattern in Bash

if [[ $strtotest == [0-7][0-7][0-7] ]]; then
    echo "Found it"
fi

Upvotes: 1

mata
mata

Reputation: 69032

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

Upvotes: 7

Douglas Leeder
Douglas Leeder

Reputation: 53310

  1. Your regex is very broken: [ ] define a range, and all characters in it are in the set that is allowed.
  2. grep has some extra quoting rules that may require extra \.
  3. grep searches for your regex within each line - if you want to only match at the start of the line you need ^ as the first char in the regex, and if you want to match to the end of the line you need a $ at the end of the regex.

Upvotes: 3

Related Questions