MacOS – Need help to understand how this find command works

command linemacos

I'm a beginner on OS X and I believe this command will make a list of all files and subfolders of specific folders

find /Volumes/Documents/ -exec stat -f "%N %Sm" {} + >~/Desktop/test.txt

I don't know how to figure out what this actually does.

Best Answer

The command you posted has two parts

  • find /Volumes/Documents/ -exec stat -f "%N %Sm" {} +
  • >~/Desktop/test.txt

The second part is easier to explain, it just writes all the output of the first one into a file called test.txt which is stored on your desktop. If you leave that part out, the result of find will be directly written into your Terminal window.

The first part is the actual find command. A call to find basically gets two kinds of parameters

  • one or several paths acting as starting point for the search (/Volumes/Documents/ in your case)
  • one or several expressions aka "find commands" which get applied to every file/folder found

A simple version would look like find /Volumes/Documents/ -print which just prints every file/folder found.

In your example the expression part is a bit more elaborated:

  • -exec runs a command on the results of find (stat -f "%N %Sm" actually)

  • stat gives info about a file.

  • The -f option for stat displays information using a specified format.

  • %N %Sm is the format used by -f.

    • % means a format string.

    • N means to print the file name.

    • Sm means to print the date modified for the file.

  • {} + is replaced by as many found files/as possible in each call to stat

For more information on understanding commands, see the man page for find and stat.