Search code examples
bashmacosmacos-catalinaspotlightlocate

Make a function locate using mdfind on MacOS Catalina


Since I am using MacOS Catalina, I would like to benefit from the useful mdfind to find any files or directory matching a name.

I would like to override locate function (classical function which will be still available by typing \locate.

Here the little binary file located into ~/bin/locate :

#!/bin/bash

if [ "$2" != "" ]; then
  mdfind "kMDItemDisplayName == '*$(echo $1)*'c" -onlyin "$2"
else
  mdfind "kMDItemDisplayName == '*$(echo $1)*'c"
fi

If there is not a second argument, I would like to find all files matching $1 (first argument) and without case sensitive.

If there is a second argument, it corresponds to the path from which we want to do the research.

But this new function locate badly works. Sometimes, files are found and other times not and I don't understand why ?

How can I modify this script to match substring provided with argument $1, especially, I don't know if I have to do a $(echo $1), $(echo "$1"), echo "$1", "$1" or others things with kMDItemDisplayName option ?

I just want all substring for files to be found (and maybe if possible directories). I don't want to use Linux "locate" since I am obliged to update at each time, unlike mdfind which is always updated.


Solution

  • Not all items may have a display name, though most items seem to have one. If you are searching for a file name, use kMDItemFSName. FS means File System.

    Also I think there is no need for the echo:
    mdfind "kMDItemDisplayName == '*$1*'c" -onlyin "$2"

    And it would be helpful if you provide an example of a query that did not return a result although it should have.