Using the Find Command in Linux

There’s a powerful Linux command that can save you lots of headaches when used in the right places. It’s called find. It walks through the file tree, starting from the provided path. Next, it prints each directory and file, including its path relative to the current working directory. Let’s explore the find command in Linux together!

The basics

Just try it, enter the following and see what output you get:

$ find .

For me, the output looks like this:

.
./images
./images/cover.jpg
./scripts
./scripts/loop.sh
./scripts/arguments.sh
./scripts/words.txt

The first dot is simply the current directory. Find will both output directories and files. If you only want to list files, use:

$ find . -type f

If you only want to list directories, use:

find . -type d

Expressions

So far for the basics. The find command in Linux also takes expressions, which further narrow down what files it should return. Useful expressions that I use often are -mmin and -mtime. The following command returns all files that were modified more than 5 minutes ago:

$ find . -type f -mmin +5

And this one returns all files that were modified more than 5 days ago, because -mtime counts in days:

$ find . -type f -mtime +5

On macOS and other BSD systems, find also accepts a unit after the number, like -mtime +5m for 5 minutes. GNU find, the one on Linux, doesn’t support this and stops with find: invalid argument `+5m' to `-mtime'. So only use these units on a Mac:

ModifierMeaning
ssecond
mminute (60 seconds)
hhour (60 minutes)
dday (24 hours)
wweek (7 days)

The plus sign is important as well:

  • a preceding plus sign means “more than n”
  • a preceding minus sign means “less than n”
  • neither means “exactly n”

Another useful expression is -name, which will filter the results based on the file name. For the name, you can use a shell pattern. So the command find . -name "*.txt" will only return files with the .txt-extension. Put the pattern in quotes, so your shell doesn’t expand it before find sees it.

-name is case-sensitive, so it skips a file called README.TXT. Use -iname if you want to ignore case:

$ find . -iname "*.txt"
./README.TXT
./scripts/my notes.txt
./scripts/words.txt

Combining expressions

When you give find more than one expression, a file has to match all of them. This finds shell scripts that were modified more than 5 minutes ago:

$ find . -type f -name "*.sh" -mmin +5

Use -o for “or”, and -not to turn an expression around. You need escaped parentheses to group an “or”, because your shell would otherwise interpret them:

$ find . -type f \( -name "*.sh" -o -name "*.jpg" \)
$ find . -type f -not -name "*.txt"

Limiting the depth

By default, find goes through all subdirectories. With -maxdepth, you limit how deep it goes. -maxdepth 1 only looks in the directory itself:

$ find . -maxdepth 1 -type f
./README.TXT

-maxdepth applies to the whole search, no matter where you put it, so it’s common to write it right after the starting directory.

Actions: using the results

With our new ninja scripting powers, we can now use the Linux find command to return a bunch of files, feed them to a for loop in a Bash script, and do some awesome stuff with them, right?

True, but since it’s pretty obvious you want to perform some actions on the returned files, find has us covered already. No scripting is necessary.

Say you want to delete the files that match your criteria, you can simply add -delete to your find-command. This is obviously a bit dangerous, so before using this flag, always check the output of the find-command without it first.

Always put -delete at the end. find reads its expressions from left to right, so in find . -delete -name "*.log", the delete happens before the name check. That command deletes everything in the current directory, not just the log files. The right way is:

$ find . -name "*.log" -delete

Even safer: run find . -name "*.log" first, check the list, and then add -delete to the end.

What gives us much more flexibility, is the -exec flag. It allows us to execute any command. An example that you may have seen before is this one:

$ find /path/to/files* -mmin +5 -exec rm {} +

Let’s break it down:

  • find all files in the given path that are modified more than 5 minutes ago
  • execute the rm command (which deletes the files)
  • {} + is replaced with as many pathnames as possible for each invocation of the given utility (in our case rm)

This is actually a very efficient way of removing lots of files, like thousands or even millions.

A slight alternative to this command is:

$ find /path/to/files* -mmin +5 -exec rm {} \;

The difference is that rm is now executed for every single file, instead of as many files per batch as your system allows. Which version you use depends on the command you’re executing on the results. If you can use the one with the plus sign, it’s a lot faster! That’s because the command is executed on many files at once, saving your OS lots of CPU cycles that are needed to open, start, run, and exit a program. However, some commands take just one file at a time and for those, the second version comes to the rescue.

File names with spaces: -print0 and xargs

You’ll often see find combined with xargs, which takes a list of file names and passes them to another command. That works until you hit a file name with a space in it. xargs splits on spaces, so my notes.txt becomes two files that don’t exist:

$ find . -name "*.txt" | xargs wc -l
wc: ./scripts/my: No such file or directory
wc: notes.txt: No such file or directory
2 ./scripts/words.txt
2 total

The fix is to let find separate the names with a null character, using -print0, and tell xargs to expect that with -0:

$ find . -name "*.txt" -print0 | xargs -0 wc -l
1 ./scripts/my notes.txt
2 ./scripts/words.txt
3 total

Make it a habit to always use the two together. -exec ... {} + handles spaces correctly too, so you don’t need -print0 there.

And again: if you enter man find (or visit the online man page), you’ll get the full documentation. But I’ll admit; I tend to google this stuff too because you generally get useful examples instead of needing to plow through the raw documentation. However, always try to understand exactly what it is you’re pasting into your terminal before hitting enter!

Related articles

Leave a Comment