mdfind

On this page 7

mdfind is the command-line interface to Spotlight search in macOS: it sends a query to the system metadata index and prints the paths of every matching file, usually in well under a second. In Terminal & scripting work, it is the fastest way to locate files by name, text content, file type or any of the hundreds of metadata attributes that Spotlight records.

Unlike the classic Unix find command, which walks the directory tree and inspects each file on demand, mdfind never touches the file system directly. It asks the Spotlight server process to search an index that is already built, which makes it extremely fast but also means that its results are only as complete as the index behind them.

How mdfind queries the Spotlight index

mdfind works by passing a query to the metadata server, mds, which searches the per-volume index stored in the hidden .Spotlight-V100 folder. Importer plug-ins (the mdimporter bundles) extract text and attributes from documents, images, audio files and applications when files are created or changed, and the mdworker processes write that information into the index.

A plain argument such as mdfind invoice performs a free-text search similar to typing in the Spotlight menu: it matches file names and indexed content. A raw query expression such as mdfind "kMDItemContentType == 'com.adobe.pdf'" searches a specific attribute, and expressions can be combined with && and ||. Attribute values use Uniform Type Identifiers for file types and ISO date functions such as $time.today(-7) for relative dates.

The following table lists the options that matter most in daily administration and scripting.

OptionPurposeTypical use
-onlyin dirLimits the search to one folder treeSearch a project folder only
-name textMatches file names onlyFind a file whose name is known
-liveKeeps running and reports changesWatch for new downloads
-countPrints the number of matchesQuick inventory checks
-0Separates results with NUL charactersSafe piping to xargs -0
-attr namePrints an attribute value with each pathShow sizes or dates in results
-literalTreats the query as plain textAvoid parsing of special characters
Frequently used mdfind options

Useful metadata attributes for queries

Every indexed file carries a set of kMDItem attributes, and the companion command mdls lists them for a single file. Reading mdls output is the most reliable way to learn which attribute names and value formats a query must use, because attribute availability depends on the importer that processed the file.

AttributeMeaningExample expression
kMDItemFSNameFile name on diskkMDItemFSName == ‘*.key’
kMDItemContentTypeUniform Type IdentifierkMDItemContentType == ‘public.jpeg’
kMDItemContentModificationDateLast content change> $time.today(-30)
kMDItemFSSizeSize in byteskMDItemFSSize > 1000000000
kMDItemWhereFromsDownload source URLskMDItemWhereFroms == ‘*example*’
kMDItemAuthorsDocument authorskMDItemAuthors == ‘Smith*’cd
Common attributes and example queries

String comparisons accept modifier letters after the closing quote: c makes the match case-insensitive, d ignores diacritical marks, and w matches word boundaries. The wildcard * works inside quoted values, which allows prefix, suffix and substring matching without regular expressions.

mdfind compared with find, locate and mdls

mdfind is one of several search tools available in the macOS shell, and each tool answers a different kind of question. The table below shows where each one fits.

ToolData sourceSpeedBest for
mdfindSpotlight indexVery fastContent and metadata searches
findLive file system walkSlow on large treesExact, guaranteed results and permissions
locatePeriodic path databaseFastPath names only, often outdated
mdlsSpotlight indexInstantInspecting one file’s attributes
grep -rLive file contentsSlowRegular expressions in plain text

The practical rule is simple: use mdfind when speed and rich metadata matter, and use find when the result must be complete and authoritative, for example in security audits, cleanup scripts or searches inside excluded or unindexed locations.

Using mdfind in scripts and automation

In shell scripts, mdfind turns slow inventory tasks into near-instant lookups. Administrators use it to find application bundles by identifier, for example mdfind "kMDItemCFBundleIdentifier == 'com.apple.Safari'", which returns the installed location of an app regardless of where the user moved it. Combined with -0 and xargs -0, results can be passed safely to other commands even when paths contain spaces.

The same queries work from AppleScript, JavaScript for Automation and Shortcuts through a Run Shell Script action or do shell script. Because mdfind returns only paths, scripts usually pair it with mdls -raw -name or stat to read additional values.

  • Always quote raw queries so the shell does not expand * or $.
  • Add -onlyin to keep results focused and scripts predictable.
  • Check the exit status and the result count before acting on matches.
  • Never delete files based on mdfind output alone without a confirming test.

Limitations and troubleshooting

mdfind returns nothing from locations Spotlight does not index: folders added to Spotlight privacy exclusions, system directories, volumes with indexing disabled, many network shares and most hidden folders. Files created a moment ago may also be missing until the importers finish processing them.

SymptomLikely causeFix
No results at allIndexing disabled on the volumeCheck with mdutil -s / and enable it
Known file not foundFolder excluded from SpotlightRemove the privacy exclusion
Outdated or wrong resultsCorrupted indexRebuild with sudo mdutil -E /
Content not matchedNo importer for the file typeSearch by name or use grep
Query syntax errorUnquoted or malformed expressionWrap the whole query in quotes
Symptoms, causes and fixes

Rebuilding the index with mdutil -E is safe but can take hours on large volumes and raises CPU use during that time, so it should be done outside working hours on production machines.

The short version

Your Mac keeps a catalog of every file it can read. It records names, dates, types and even the words inside documents. Spotlight uses this catalog when you search from the menu bar.

mdfind lets you ask that catalog from the Terminal. You type what you want, and it lists where the files are. It is very fast because it does not open folders one by one. The catch is simple. If a file is not in the catalog, mdfind cannot see it.

Where it makes a difference

An IT administrator at a design studio with 40 Macs must find out which machines still hold large video project files older than one year before a storage upgrade. A find scan across each user home folder takes over 20 minutes per Mac and slows the computers noticeably during work hours.

The administrator instead deploys a short script that runs mdfind -onlyin /Users "kMDItemContentType == 'com.apple.quicktime-movie' && kMDItemFSSize > 5000000000 && kMDItemContentModificationDate < $time.today(-365)" and reports the paths and sizes. Each Mac answers in about two seconds, and the report identifies roughly 3 TB of archival candidates across the fleet. For the two machines whose external drives were excluded from Spotlight, the administrator runs find as a confirming pass, so no relevant files are missed.