What You Need to Know to Delete Files & Directories on the Linux Command Line

The Linux command line can be a great place to work when you know what you’re doing. But when you know what you want to do, but just can’t work out the syntax or decipher the often less-than-helpful errors to get it done, it can be infuriating. So, I’ve decided to write a series of short posts explaining some of the basics for people who just want to get in, do a job, and get out, without having to spend hours learning every nuance and arcane switch.

In today’s installment we look at what you need to know to delete files & directories (a.k.a. folders).  

To delete a single file, just type:

rm filename

…where filename is whatever file you want deleted. (Include the file’s complete path if it’s not in the folder you’re currently sitting in. (Bonus tip: you can tell where you are by typing pwd (abbreviation for “Print Working Directory” or “Place Where I Dwell”) at the prompt!))

That won’t work for directories though, so for that you’ll need to use the rmdir command like this:

rmdir /directory/

…but that only works on empty directories, so be sure to delete all files within it first.  You can also use wildcards in file names like * or ? to get rid of lots of files at once, so you might do this:

rm *.txt

If you want to delete a directory and all of its files and subdirectories type:

rm -rf /some_directory_name/some_other_directory/

…You may need to preface that with sudo first, if you’re deleting files that aren’t already yours.

If you can’t delete a file that you own and have full (a.k.a. 777) permissions on it, then you probably need to set permissions for the directory that file is in.  So, for example, if you’re only at 555 permissions on the file’s directory, then being 777 on the file won’t be enough to let you delete it.

The great, but dangerous, thing about Linux is it will do exactly what you tell it to do, so be careful!  Especially with that last command!

Steve