1

I would like to know if and how it is possible to skip certain directories during an rm -rf operation.

So for example, this location contains the following subfolders (not really this is just for example):

foo
bar
elf
qrs

During my script which executes rm -rf * in this directory, I would like to know if it is possible to (for example) skip deletion of elf.

Normally, I could just pass each directory to the command with rm -rf foo bar qrs, however my scenario is, since this is in a script for many different systems, every system will have different folders. For example, system 1 may contain these:

foo
bar
elf
qrs

While system2 may contain these:

ubt
dbn
arc
elf
gnt

I would like the rm -rf command to be the same for both; deleting everything apart from elf.

Is this in any way possible?

Thank you in advance.

3
  • You can use " find . | grep -v "elf" | xargs rm -rf " in the parent directory wherein you want to delete items recursively. Commented Jun 7, 2020 at 17:35
  • Is the find -type d ! -name "elf" -delete may be the option for your case? Commented Jun 7, 2020 at 17:36
  • @danielleontiev Yes. Quite concise and useful. Didn't know that. Commented Jun 7, 2020 at 17:38

2 Answers 2

5

According to this there is no built exclude functionality to rm. However, the article details multiple methods using some shell commands to achieve the same result.

The first seems most applicable for you:

Delete all files except the file called important.txt:
rm !(important.txt)

2
  • Thanks, this works 100%. I did add -rf to the command to make: rm -rf !(elf), and it works.
    – Daniel M.
    Commented Jun 7, 2020 at 17:46
  • But the question is about deleting folders, and not files, am I getting something wrong? Commented Mar 31, 2022 at 11:03
5

One of the possible solutions:

find -type d ! -name "elf" -delete
1
  • 2
    Thanks, this also works. Shame it won't let me accept 2 answers. But I've upvoted it :)
    – Daniel M.
    Commented Jun 7, 2020 at 17:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .