Terminal: Using “lsof” When Files Won’t Delete

| TMO Quick Tip

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.

Sign Up for the Newsletter

Join the TMO Express Daily Newsletter to get the latest Mac headlines in your e-mail every weekday.

Comments

jbruni

lsof will show you open files and sockets for processes that you own. If you want to see ALL open files and sockets, you need to run lsof as root using the sudo command.

Allen Bennett

Mountain Lion will ask you if you want to force eject a disk with busy files. I use sudo rm -f to remove stubborn files from the trash as sometimes VLC or Preview or TextEdit don’t let go properly on quiting. You can drag the file on the terminal window after the space on the above command, just like in the article.

Capn

If you don’t care what program is using the file that won’t delete, you can easily delete it without opening terminal.

Just go to Finder in the menu bar and hold down ‘option’ when you click ‘Empty Trash’.  This will empty the trash immediately with no confirmation (this also works if you click ‘Empty’ in the trash’s finder window).

Log-in to comment