Sub topic 14
Querying metadata and searches from Terminal
Everything you built in Finder is also reachable from the command line. Tags, smart folders, and Finder searches all rest on the Spotlight index, and Terminal has direct tools for reading it. This chapter shows how to read tags, run the same queries a smart folder runs, and read saved searches. It also covers the first checks to make when results look wrong.
This chapter assumes you know the earlier ideas: tags are labels stored as file metadata, smart folders are saved searches, and Spotlight maintains the index behind both. You should also be able to open Terminal, type a command, and quote a path that contains spaces.
The tools and what each one reads
Four commands cover most of what you need.
| Command | What it does | Reads from |
|---|---|---|
| `mdls` | Prints the metadata attributes of one file | The file's Spotlight record |
| `mdfind` | Runs a search query and prints matching paths | The Spotlight index |
| `plutil` | Prints or extracts values from a property list | A `.savedSearch` file |
| `mdutil` | Reports or changes indexing status for a volume | The Spotlight service |
Reading a file's tags with mdls
mdls prints the attributes Spotlight holds for a single file. To ask for one attribute, pass -name. The tag attribute is kMDItemUserTags:
mdls -name kMDItemUserTags ~/Documents/report.pdfThis is the same data Finder uses when you search by tag. The output is a parenthesized list. A file with two tags looks like this:
kMDItemUserTags = (
Red,
Project
)A file with no tags prints kMDItemUserTags = (null). Built-in color tags may show a trailing number after the name, such as "Red\n6". The number records the tag's color. When you write queries, use the plain name, as in the next section.
For scripting, add -raw to drop the name = prefix. Add -nullMarker "" if you want an empty string instead of (null).
You can list every attribute of a file by running mdls with just the path. The list is long. It is useful for finding attribute names you can use in smart folder criteria, such as kMDItemKind or kMDItemLastUsedDate.
Running a search with mdfind
mdfind takes a query and prints the path of each match. The -onlyin option limits the search to one folder. This query finds files under Documents that carry the tag named Red:
mdfind -onlyin ~/Documents 'kMDItemUserTags == "Red"'Wrap the whole query in single quotes. The shell then passes the inner double quotes through to mdfind untouched.
Date criteria use the $time helpers. This query finds files modified in the last seven days, which is the kind of criterion a smart folder saves:
mdfind -onlyin ~/Documents 'kMDItemFSContentChangeDate >= $time.today(-7)'Other helpers include $time.now(), $time.yesterday, and $time.this_week. Each takes an optional offset in the same way as today(-7).
Query syntax
A query is an attribute, an operator, and a value. These parts matter most in practice:
- Operators are
==,!=,<,>,<=, and>=. - Combine tests with
&&(and) and||(or). Group them with parentheses. - The
*wildcard matches any run of characters, as in"*report*". - Modifiers after the closing quote change matching.
cignores case anddignores diacritics. Write"red"cdto matchRed,red, and so on.
Here is a combined query. It finds PDFs that carry the Project tag, matching the tag name without regard to case:
mdfind -onlyin ~/Documents 'kMDItemUserTags == "project"c && kMDItemContentType == "com.adobe.pdf"'Useful options
| Option | Effect |
|---|---|
| `-onlyin DIR` | Restrict the search to a folder |
| `-count` | Print only the number of matches |
| `-name TEXT` | Match on file name only |
| `-0` | Separate results with a null byte, safe for names with spaces |
| `-live` | Keep running and print changes as the index updates |
-count is a quick sanity check before you print a long list. -live behaves like a smart folder, because it updates as files change. Press Control-C to stop it.
To act on results safely, pair -0 with xargs -0. This example prints the size and name of each Red-tagged file:
mdfind -0 -onlyin ~/Documents 'kMDItemUserTags == "Red"' | xargs -0 ls -lhReading smart folders from disk
When you save a smart folder, Finder writes a .savedSearch file. The default location is the Saved Searches folder in your Library. List it with:
ls ~/Library/Saved\ SearchesThe backslash escapes the space in the folder name. Quoting the whole path works too. Each file is a property list. This command prints a saved smart folder, here one named Recent Documents, so you can read its stored search query and criteria:
plutil -p ~/Library/Saved\ Searches/Recent\ Documents.savedSearchYou will usually see a RawQuery key and a SearchCriteria key. RawQuery holds the Spotlight query string that mdfind understands. SearchCriteria holds the settings Finder shows in the criteria rows, including the search scope. The exact keys can vary between macOS versions. Use plutil -p to see what your system wrote.
Running a saved search from Terminal
Extract RawQuery and pass it to mdfind. This reproduces the smart folder's results without opening Finder:
query=$(plutil -extract RawQuery raw -o - ~/Library/Saved\ Searches/Recent\ Documents.savedSearch)
mdfind "$query"Quote "$query" so the shell keeps it as one argument. The folder may also limit where it searches. If so, add -onlyin with the same folder to get matching results.
This approach is useful for three jobs:
- Checking whether a smart folder's query is correct, separately from Finder's display.
- Counting matches in a script with
mdfind -count. - Copying a query you built in Finder into a shell script.
Checking indexing and tag storage
When a tag search or smart folder returns too little, check the index first. mdutil reports whether Spotlight is indexing a volume:
mdutil -s /The output says Indexing enabled. when the volume is indexed. If you see Indexing disabled., searches for files on that volume return nothing new. Turning indexing back on or rebuilding it needs administrator rights and changes system state, so decide that deliberately. Folders added to Spotlight's privacy exclusions in System Settings are also left out of every search.
Tags have a second location besides the index. Each file stores its tags in an extended attribute named com.apple.metadata:_kMDItemUserTags. You can see whether a file carries the attribute with:
xattr -l ~/Documents/report.pdfThe value is a binary property list, so it prints as bytes. The point of the check is the comparison:
- If
xattrshows the attribute butmdlsreports(null), the file is not indexed yet, or its index record is stale. - If neither shows a tag, the file is not tagged. This also happens when a copy method dropped the extended attributes. Some tools do this when moving files to non-Apple file systems.
A short diagnostic routine
When a smart folder or tag search looks wrong, work from the file outward:
- Run
mdls -name kMDItemUserTagson a file you expect to match. Confirm the tag is there. - Run the equivalent
mdfind -onlyinquery on its folder. If the file appears, the index is fine. - If the file is missing, run
mdutil -s /and check the Privacy list in System Settings. - Run
plutil -pon the.savedSearchfile and compare itsRawQuerywith the query you tested.
This sequence separates three causes that look the same in Finder: a missing tag, a stale index, and a mistaken query.
Exercise
A smart folder named Open Tasks should show every file tagged Red under Documents. It shows nothing, though you can see a Red tag on report.pdf in Finder. Which three Terminal commands, in order, would you run to find out whether the problem is the tag, the index, or the query?
Show answer
First run mdls -name kMDItemUserTags ~/Documents/report.pdf to see whether Spotlight reports the Red tag. Second run mdfind -onlyin ~/Documents 'kMDItemUserTags == "Red"' to see whether the index returns the file. Third run plutil -p ~/Library/Saved\ Searches/Open\ Tasks.savedSearch and compare its RawQuery with the query you just tested. If mdls shows (null), the index record is missing or stale. If mdls shows the tag but mdfind finds nothing, check mdutil -s / and the Privacy exclusions. If mdfind finds the file, the saved query or its scope is the problem.