Learn how to use find command in Linux to search for files and directories based on multiple criteria using logical operators AND, OR, and NOT
- Criteria are ANDed together by default.
- Can be OR’d or negated with -o or –not
- Parentheses can be used to determine logic order, but must be escaped in bash
find -user joe -not -group joe
find -user joe -o -user jane
find -not \( -user joe -o -user jane \)
By default, if multiple criteria are given to find, they must all apply to a file for it to be considered a match.
For example, the following will only match files whose names end in .png AND are owned by the user oliver:
[user@user-pc ~]$ find / -name "*.png" -user oliver
This behavior can be overridden with the -o option. The following command will match files whose names end in .png OR are owned by oliver:
[user@user-pc ~]$ find / -name "*.png" -o -user oliver
find also includes a logical “not” operator. Options preceded with a ! or the -not option will cause find to look for the opposite of the given criterion. So the following command will match files whose names end in .png and are NOT owned by oliver.
[user@user-pc ~]$ find / -name "*.png" -not -user oliver
With the addition of logical operators, the question of operator precedence is raised. Logical ANDs have a higher priority than logical ORs, and logical NOTs have the highest priority of all. To force precedence of an expression, you can enclose options that should be grouped together in parentheses. Make sure to put spaces after the \( adn before the \)
or find will not work as expected. The find man page has more details about this in the OPERATORS section.