Find by Attributes

This post introduces how Linux command find is used to find file or directory with certain attributes.

Previously, I always pip the output of find to grep to search for files having certain pattern in the name. It works just fine until today I want to find a folder owned by certain group. Then I realize that I should have used find in a more powerful way, without learning too complicated command format. Here comes the skeleton of find command:

find <path> [expression]

where the [expression] is a group of attribute selectors glued by logic operators. Some of the attribute selectors are listed in the following table:

selector options
-type ‘f’ for file, ‘d’ for directory, ‘l’ for link, ‘b’, ‘c’ are device type
-perm oct code or multiple u/g/o=r/w/x, could be decorated by prefix ‘/’ or ‘-‘
-user user name
-group group name
-name file name, could contain wildcards (*?)
-iname case-insensitive file name
-size file size

Logic operators are ! or -not, -o or -or, -a or -and (and can be ommitted as default logic). The output could follow the long version of ls as long as you add the -ls option.

Here are some examples:

find -type d -group root   # find all subdirectories belongs to root recursively from current path
find ./ -perm 777   # find files/directory with exact permission 777 recursively from current path
find -perm -u=w,g=w  # equivalent of -perm -220 that both owner and group have at least write permission
find -perm /644  # owner has read or write permission, or group or others have read permission
find -name "2019*" -o -iname "*c++"  # find all whose name begains with 2019 or contains c++ or C++
find . -size +4G -exec ls -lh {} \; # find then list all files bigger than 4GB

Note: -exec allows to trigger execution of commands with the file found match.

Credits