Sub topic 14
Spotlight from Terminal: mdfind and mdls
This chapter assumes you can open Terminal and run commands, and that you know how Spotlight indexes files and metadata from earlier chapters. You will use the command-line tools that read the same index Spotlight uses. mdfind searches the index. mdls shows the metadata stored for one file. mdutil checks and manages indexing.
Why use Spotlight from Terminal
The Spotlight window is good for one-off searches. Terminal is better when you want to do one of these things:
- Pipe search results into another command, such as
wc -lorxargs. - Limit a search to one folder and get a plain list of paths.
- Use metadata that the Spotlight window does not expose directly.
- Script a repeatable search.
All three tools talk to the same index. If Spotlight cannot find a file, mdfind cannot find it either. A file missing from mdfind output usually means it is not indexed, not that the command is wrong.
Searching by name with mdfind
The simplest form searches the whole index for a word:
mdfind invoiceThis matches file names, file contents, and some metadata, just like the Spotlight window. It can return a long list. To match only file names, add -name:
mdfind -name "invoice"-name matches the file name only, so a PDF whose text contains "invoice" but whose name does not is left out. The match is not case sensitive and also matches names that contain the word, such as invoice-2026.pdf.
Output is one full path per line. Because paths can contain spaces, quote them when you reuse them in other commands.
Limiting the search to a folder
Without a limit, mdfind searches every indexed volume. Use -onlyin to restrict it to a folder and everything below it:
mdfind -onlyin ~/Documents "budget"You can combine -onlyin with -name:
mdfind -onlyin ~/Downloads -name "receipt"Searching a single folder is faster and produces less noise. It still depends on the index, so the folder must not be excluded in Spotlight settings.
Structured queries on metadata
A plain word is a loose match. A structured query tests a specific metadata attribute. Attribute names start with kMDItem. This query returns only PDF files in Documents:
mdfind -onlyin ~/Documents "kMDItemContentType == 'com.adobe.pdf'"The pieces are:
kMDItemContentTypeis the attribute being tested.==is the comparison.'com.adobe.pdf'is the value, written in single quotes. The whole query is in double quotes so the shell passes it as one argument.
The content type is a Uniform Type Identifier (UTI), a standard name for a kind of file. Other common values are public.jpeg for JPEG images, public.plain-text for plain text, and com.apple.application-bundle for apps.
Comparison operators and modifiers
You can use several comparisons in a query:
| Form | Meaning | Example | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| `==` | Equal to | `kMDItemFSName == 'notes.txt'` | ||||
| `!=` | Not equal to | `kMDItemContentType != 'public.jpeg'` | ||||
| `<`, `>` | Less or greater than | `kMDItemFSSize > 10000000` | ||||
| `&&` | Both conditions | `kMDItemContentType == 'com.adobe.pdf' && kMDItemFSSize > 1000000` | ||||
| `\ | \ | ` | Either condition | `kMDItemFSName == 'a.txt' \ | \ | kMDItemFSName == 'b.txt'` |
A string value can end with a modifier in brackets. c ignores case, and d ignores diacritics such as accents. Wildcards use *:
mdfind -onlyin ~/Documents "kMDItemFSName == '*report*'c"This finds files in Documents whose name contains "report" in any capitalization. The c after the closing quote makes the match case insensitive.
Dates
Date attributes accept the special value $time.today, with an offset in seconds. This finds files in Documents modified within the last 24 hours:
mdfind -onlyin ~/Documents 'kMDItemFSContentChangeDate >= $time.today(-1)'The query is in single quotes here so the shell does not expand $time as a variable. Use single quotes around the whole query whenever it contains a $. If you also need a single quote inside the query, switch back to double quotes and escape the dollar sign as \$time.
Inspecting metadata with mdls
To write a structured query you need the attribute names and values. mdls prints every attribute Spotlight has stored for one file:
mdls ~/Documents/report.pdfThe output is a list of name = value lines. A few lines from a PDF might look like this:
kMDItemContentType = "com.adobe.pdf"
kMDItemFSName = "report.pdf"
kMDItemFSSize = 482113
kMDItemNumberOfPages = 12Use this output as a reference. Copy an attribute name and value into an mdfind query to find similar files. For example, if you want every document with a certain page count, find the attribute in mdls output first, then test it:
mdfind -onlyin ~/Documents "kMDItemNumberOfPages > 50"To print one attribute, use -name. Add -raw to remove the label:
mdls -name kMDItemContentType ~/Documents/report.pdf
mdls -raw -name kMDItemFSSize ~/Documents/report.pdfDifferent file types have different attributes. A photo has camera and dimension fields, a song has artist and album, and a PDF has page count. If an attribute shows (null), the file does not have a value for it.
Combining the tools in scripts
Because mdfind prints one path per line, it works with ordinary shell tools. Count the PDFs in Documents:
mdfind -onlyin ~/Documents "kMDItemContentType == 'com.adobe.pdf'" | wc -lPaths with spaces break simple pipelines. Use -0 to separate results with a null character, and xargs -0 to read them safely:
mdfind -0 -onlyin ~/Downloads "kMDItemContentType == 'com.adobe.pdf'" | xargs -0 ls -lhYou can also list the size of each match with mdls:
mdfind -0 -onlyin ~/Documents "kMDItemContentType == 'com.adobe.pdf'" \
| xargs -0 -n 1 mdls -name kMDItemFSName -name kMDItemFSSize-n 1 runs mdls once per file so each result is labeled with its own file.
Checking and rebuilding the index with mdutil
When mdfind returns nothing for a file you know exists, check whether indexing is on for the volume:
mdutil -s /The output reports the volume and its state, for example "Indexing enabled." If it says indexing is disabled, results will be empty or stale.
To rebuild the index for the startup volume, erase it and let macOS recreate it:
sudo mdutil -E /The command needs administrator rights. After it runs, Spotlight re-reads every file. This can take a long time on a large disk and uses extra CPU, so searches are incomplete until it finishes. Run it only when results are missing or stale and simpler fixes have not worked. It does not delete your files. It deletes only the index.
Common errors
| Symptom | Likely cause | What to do |
|---|---|---|
| No output | Folder excluded, file not yet indexed, or indexing off | Run `mdutil -s /` and check Spotlight privacy settings |
| Shell error about unexpected tokens | Unquoted parentheses, `&&`, or `*` in the query | Put the whole query in quotes |
| `$time` expands to nothing | Double quotes let the shell expand `$` | Use single quotes around the query |
| Name query returns too much | Plain word searches contents too | Use `-name` or `kMDItemFSName` |
| Attribute query returns nothing | Misspelled attribute or wrong value type | Copy the exact name and value from `mdls` |
Summary of the tools
| Tool | Purpose | Typical use |
|---|---|---|
| `mdfind` | Search the index | `mdfind -onlyin ~/Documents -name "invoice"` |
| `mdls` | Show metadata for one file | `mdls ~/Documents/report.pdf` |
| `mdutil` | Show or change indexing | `mdutil -s /` |
Exercise
You want a list of every PDF in ~/Documents larger than about 5 MB (5000000 bytes). Write the command, and say how you would find the right attribute names if you did not remember them.
Show answer
Run mdfind -onlyin ~/Documents "kMDItemContentType == 'com.adobe.pdf' && kMDItemFSSize > 5000000". To find attribute names, run mdls on a sample PDF, such as mdls ~/Documents/report.pdf, and read the kMDItemContentType and kMDItemFSSize lines.
Exercise
mdfind -name "budget" finds nothing, but you can see budget.xlsx in Finder in a folder you excluded from Spotlight. Why, and what are two ways to confirm or fix it?
Show answer
Excluded folders are not indexed, and mdfind reads only the index. Confirm by checking the folder in the Spotlight privacy settings, or by running ls on the folder. Fix it by removing the folder from the exclusion list so Spotlight indexes it again.
Exercise
Why does mdfind "kMDItemFSContentChangeDate >= $time.today(-1)" fail to return the expected files, and how do you correct it?
Show answer
Inside double quotes the shell expands $time as an empty variable, so the query is changed before mdfind sees it. Put the query in single quotes: mdfind 'kMDItemFSContentChangeDate >= $time.today(-1)'.