Q: Is there anyway to run the rm command (or rm -rf) and exclude one file?

A: There is no native exclude option for the rm command in Linux. You can however string some commands together in order to accomplish the same effect.

You can exclude files by using any wildcard or globbing patterns. This my favorite, and in my opinion, the most elegant way to accomplish this. However, it may not work on all systems depending on your configuration. It should work on all modern Linux systems out of the box.

Examples of How to Exclude a File From Deletion

Delete all files except the file called important.txt:

rm !(important.txt)

In this example, we delete everything except files with the .txt extension.

rm !(*.txt)

Remove all files, except those that start with the letter h (case sensitive):

rm !(h*)

Delete all files that start with a digit:

rm [0-9]*

To Delete all files but exclude those files that start with a digit.

rm !([0-9]*)

Delete all files that start with a lowercase a through c

rm [a-c]*

If you do not have Bash Extended Globbing enabled, here are some sure fire ways to accomplish the same task.

To learn more about globbing, read our article Standard Wildcards and Globbing Patterns.

Let's say you have a directory full of files and you want to delete them all except a single file called important.txt. You could use command substitution like this.

rm -f $(find . -maxdepth 1 -type f -name "*" ! -name "important.txt")

If you want to delete all files in the current directory and sub-directories and exclude a file from the rm command, you can do something like this.

NOTE: Using -rf will delete files and directories recursively without asking permission. This will destroy all files in the current directory and sub-directories. You should always avoid using -rf if possible.

rm -rf $(find . -name "*" ! -name "important.txt")

Another way of accomplishing this is by using find with exec, like this:

find . -maxdepth 1 -type f ! -name "important.txt" -exec rm {} \;

Be careful and have fun!

To learn more about the rm command and it's option read "How to use the Linux rm Command".