Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I need to delete all the content of a folder in Centos, but no the folder, for example I have a folder named MYFOLDER inside I have a lot of folders like FOLD_1, FOLD_2, FOLD_3, FOLD_4... etc , and some files like file_1.txt, file_2.log, etc, now that I need is delete all these folders and files, but no the container folder, this is the MYFOLDER folder, cause I need this directory to direct the results of a previous process.

I tried with the rm -rf command, but this delete the container folder too.

share|improve this question
add comment

4 Answers

up vote 2 down vote accepted

Delete the contents of the folder instead.

rm -r MYFOLDER/*
share|improve this answer
1  
Note that this doesn't hidden files/directories within MYFOLDER –  tylerl Oct 24 '11 at 14:33
    
thanks so much..!! ;) –  verofairy Oct 24 '11 at 15:31
1  
@tylerl: It does if you set shopt -s dotglob first. –  jgoldschrafe Oct 25 '11 at 3:33
add comment

You can use:

rm -r MYFOLDER/{.[^.],.??*}

This deletes also the hidden files and folders. If you have too many files in the MYFOLDER directory, then you should run instead:

ls MYFOLDER/{.[^.],.??*}|xargs rm -r
share|improve this answer
add comment

The easiest way, in my opinion, is to delete the entire directory, including itself, and then recreate the folder. There are situations when this is not a good solution (such a unattended scripts or more complex pipelines), but you didn't specify why you didn't want to delete the folder.

rm -rf foldername
mkdir foldername

Oops. You did specify (i reread your post). Well,still, deleting and recreating can work. Especially if you chain commands together, like

rm -rf foldername && mkdir foldername

Or

rm -rf foldername; mkdir foldername
share|improve this answer
    
Sometimes you do not have permission in the parent folder or you want to preserve certain attributes you are unaware of. E.g. you can not delete your home folder as non root user, but you can remove anything under it. –  Mircea Vutcovici Oct 28 '11 at 22:10
add comment

How about

cd MYFOLDER
find . | rm -rf

This deletes hidden files (the ones starting with a dot), too.

share|improve this answer
    
This will delete MYFOLDER too. –  Mircea Vutcovici Oct 28 '11 at 22:12
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.