Tuesday, April 30, 2024
90
rated 0 times [  90] [ 0]  / answers: 1 / hits: 229366  / 3 Years ago, fri, august 6, 2021, 5:29:56

Is there a command to remove all files and subdirectories in a directory without deleting the directory?



For example if I have directory dontDeleteMe with subdirectories 1, 2, 3 and each subdirectory has a few pictures in it, how can I remove the subdirectories 1, 2, and 3 and all the files in the them, without removing the parent directory dontDeleteMe?


More From » command-line

 Answers
1

To remove everything in a directory without removing the directory, type in:



rm -rfv dontDeleteMe/*


Please note, the /* part is very important. If you put a space before the *, it will delete all your files in your current directory.



Also, be very careful playing with rm, -r and * all in the same command. They can be a disastrous combination.



Update: Okay, I realized if you do have hidden/dot files [filenames with dots at the beginning, e.x. .hidden] then this will leave those files intact.



So really, the simplest solution to the original question is:



rm -rfv dontDeleteMe && mkdir dontDeleteMe


Another one would be to use find's -exec option or pipe to xargs (below):



find dontDeleteMe/* -print0  | xargs -0  rm -rv

[#42542] Friday, August 6, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
barted

Total Points: 424
Total Questions: 103
Total Answers: 101

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
;