Mac OS: Auto-archive Your Files

Tired of having a messy desktop? You can automatically sort your files into an archive using Applescript or Bash, on Mac OSX.

Goal: Move files that haven’t been modified in 2 weeks to an archive folder called “Old”, and to make the folder “Old” if it doesn’t exist.

Here is the Applescript code to accomplish this:

set ageInDays to 14 -- Files are this many days or older since they were modified
set source_folder to path to desktop
set target_folder_name to "Old"
set target_folder to ((source_folder as string) & target_folder_name & ":")

set ageInDays to (current date) - (ageInDays * 24 * 60 * 60)

tell application "Finder"

	if (not (exists folder target_folder)) then
		make new folder at source_folder with properties {name:target_folder_name}
	end if

	set theitems to every file of folder (source_folder)

	repeat with x in theitems

		if modification date of x < ageInDays then
			move x to target_folder
		end if

	end repeat

end tell

I put the names of the folders in variables because we’ll need to access them in two different ways, first for creating a folder when needed and then to move the files. Also, the variable “ageInDays” needed to be converted to a format that Finder wants to read, the time in seconds not days.

And here the same thing using a shell script within Applescript:

set ageInDays to 14
do shell script "mkdir -p ~/Desktop/Old/ && find ~/Desktop -mtime +" & ageInDays & " -maxdepth 1 -type f -exec mv {} ~/Desktop/Old/ \;"

Shockingly different, right?

Just the shell script, to be run outside of Applescript would be:

mkdir -p ~/Desktop/Old/ && find ~/Desktop -mtime +14 -maxdepth 1 -type f -exec mv {} ~/Desktop/Old/ ;

Shell Command Explanation

Here’s what’s going on. There are two commands.

The first command, mkdir creates a directory. The -p after it helps it to not error when the file already exists. The last part ~/Desktop/Old/ is the folder we want to make. In Mac terms,  “~/” is your home folder.

We separate the two commands with double ampersands, &&.

Next, the find command — which, not surprisingly, finds files. ~/Desktop is the  location we want to start searching in. -mtime +14 is the number of days in the past the file was modified, e.g. more than 14 days ago. If we changed this -14 then it would search for files that were modified within the past 14 days. The option -mtime is convienently in days, not seconds, however there is an option for that. -maxdepth 1 tells the command how many folders deep to search, in this case only the first level – so “1” is what we use. -type f is a very handy option, only grabbing files and ignoring folders. -exec … ; is the last part, which extends the found results to a command, in this case mv (move).

Leave a Reply

Your email address will not be published. Required fields are marked *