Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the file "date added" in terminal

Tags:

terminal

macos

In my downloads folder on my Mac the files have a "Date Added" column.

I'm trying to create a script to move files that are older than x days to my trash folder. The following works but it is pulling the files based on created/modified date, not the "Date Added" that I see from Finder. Is there a way to display/use this "Date Added" field?

find /users/home/downloads -maxdepth 1 -mtime +365 -type f -exec mv "{}" /destination/ \;

It looks like with the STAT command you have to list the filename for it to work.

like image 357
Mitch Avatar asked Nov 16 '18 16:11

Mitch


2 Answers

"Date Added" is stored in the metadata attribute kMDItemDateAdded. From the terminal, it can be retrieved using the mdls command:

mdls -name kMDItemDateAdded <filename>

will return something like

kMDItemDateAdded = 2022-01-03 16:40:14 +0000

If you add -name kMDItemFSName, it will also return the file name and thus can be used with wildcards in the filname (or just *).

Limitation:

While this should be working for the scenario described in the question, it seems that mdls does not return this attribute for files that are excluded from Spotlight search scope, like for example files in Trash, even though they do have that attribute, as can be seen in Finder. So there is probably a better answer than this which covers all files, no matter if they are in the Spotlight index or not.

See also How can I find out when a file had been moved to trash?

like image 60
not2savvy Avatar answered Nov 15 '22 11:11

not2savvy


Note: I am leaving up this answer in case the distinction between "ctime" and "birthtime" is useful, but commenters and this newer answer have suggested that neither is actually always identical to the "Date Added" in Finder.


In the stat structure, "Date Added" is st_ctime (which is the "time of last change of file status information") while "Date Created" is st_birthtime.

Other Mac (really BSD) commands can access either of these. For example ls -ltc Downloads | head will list the most recently "Added" files, while ls -ltU Downloads | head will list the most recently "Created" files.

Similarly find Downloads -maxdepth 1 -ctime -2 will find files "Added" in the last 2 days, while find Downloads -maxdepth 1 -Btime -2 will find files "Created" in the last 2 days.

I suspect the command you want is

find /users/home/downloads -maxdepth 1 -ctime +365 -type f -exec mv "{}" /destination/ \;

Note the use of -ctime.

like image 45
Robert Tupelo-Schneck Avatar answered Nov 15 '22 11:11

Robert Tupelo-Schneck