Move files to the trash with a Swift script

Swift 3

I really don’t like using the ‘rm’ shell command – one misplaced character and you can do some serious damage. But when working in the Finder I don’t think twice about deleting files, because I know I can always get them back from the trash. So here is a Swift shell script which does exactly that – it moves files to the trash instead of deleting them permanently.

The syntax is very simple – all parameters refer to file system items which should be moved to the trash:

The code (gist)

The script is based on this gist but updated for Swift 3 and uses SwiftShell for output to standard error. The actual work of moving the files to the trash is performed by NSWorkspace.sharedWorkspace().recycleURLs. Since this is an asynchronous method we need to launch it in a Grand Central Dispatch block and then have the run loop wait until the method is finished so we get a chance to print any errors before the script exits.

We call removeDuplicates on the arguments list to avoid an error message if we try to trash the same file item twice. Then in the callback from recycleURLs we check for errors – if there are any we print the names of the file items that could not be trashed, and then the error.

  • Update 2016–10–09: converted to Swift 3.
  • Update 2017-04-28: updated to SwiftShell 3.0.