Terminal: Using "lsof" When Files Won't Delete

One of the handiest Terminal tricks I know is using the lsof (list open files) command to figure out what's causing this annoying issue:

There are quite a few ways you could deal with your Trash doing this, such as logging out and in again (which will usually fix the problem), but lsof is my favorite. I like knowing what's going on behind the scenes, OK? And I don't like logging out if I don't have to. Humbug. Humbug, I say.

So here's what you'll do. Once you see that message, open Terminal (it's in Applications > Utilities) and type in "lsof" (without the quotes).

Type a space after that command, then open your Trash. Drag the file that's refusing to delete to the Terminal window and drop it to make the path fill in automatically.

Press Return, and after a couple of seconds, Terminal will give you information that looks like this:

In that very first column, it's telling me that Preview is the program that thinks it's using the file. If I then quit or force-quit Preview, I should be good to go!

A similar useful trick with lsof is figuring out why you can't eject a disk. These days, OS X will tell you what program is keeping the disk mounted most of the time…

…but if you don't get that message (or if you're running an earlier version of the OS), lsof can be helpful here, too. Just do everything you did before, but drop the mounted disk from your Desktop or Finder's sidebar onto the Terminal window instead.

And just like with the file that wouldn't delete, you'll be given info on what program might be accessing the disk and preventing you from ejecting it. Neat, huh? I've said before that I love the Terminal, and I really do. It's unrequited love, but I'm OK with that.

What? I take what I can get.