3

I know what the find command is for but I can't figure out the parentheses are for. Please explain.

3
  • I'd say they make no sense, but I might be wrong...
    – Byte Commander
    Mar 6, 2017 at 22:12
  • The pattern includes parenthesis. It looks for (pattern).
    – Pilot6
    Mar 6, 2017 at 22:18
  • 1
    @Pilot6 the search pattern may not be placed after -ls though. It's also not specified what kind of pattern it would be (e.g. -name, -iname, -regex, -path, ...)
    – Byte Commander
    Mar 6, 2017 at 23:20

1 Answer 1

7

That is a feature of find that lets you group different tests together. For example:

find . \( -name foo -or -name bar -o -name baz \) -size +1M

The parentheses need to be escaped (\( and \) instead of ( and )) because parentheses are special characters for the shell (they are usied to run commands in subshells), so they need to be escaped in order to be passed to find and not "eaten" by the shell.

The command above will find any file whose name is any of foo, bar or baz and whose size is > 1M. Now, take this directory structure as an example:

$ ls -lh *
dir1:
total 2.0M
-rw-r--r-- 1 terdon terdon 1.0M Mar  7 01:24 bar
-rw-r--r-- 1 terdon terdon 1.0M Mar  7 01:24 foo

dir2:
total 4.0M
-rw-r--r-- 1 terdon terdon 2.0M Mar  7 01:24 file
-rw-r--r-- 1 terdon terdon 2.0M Mar  7 01:24 foo

There are two files there named foo, but only one is >1M in size. There are 2 files that are >1M in size, but only one is named foo, bar, or baz. Therefore, I expect the command above to only return dir2/foo as, indeed, it does:

$ find . \( -name foo -or -name bar -o -name baz \) -size +1M
./dir2/foo

OK, but what if I run it without the parentheses?

$ find .  -name foo -or -name bar -o -name baz  -size +1M
./dir2/foo
./dir1/bar
./dir1/foo

That finds me all files named foo, all files named bar and all files named bar whose size is > 1M. So, the bar and foo in dir1 are returned even though their size is < 1M.

So, the parentheses are very useful for crafting a find command that combines different sets of tests. When combined with find's -or, -and and -not operators, this makes for an extremely powerful tool.

What they do in your example I cannot tell since you don't actually give a working command as an example. It will depend on what pattern is. If you're really using find . -ls and then, after that, another set of tests in parentheses, then they do nothing since find . -ls already matches and lists all files and directories.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.