Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I want to remove a folder contents and it's sub-folder contents without removing hidden files in folder and sub-folders. How can i do it by using shell script??

I have tried rm -rf foldername but it is removing entire contents.

share|improve this question

migrated from stackoverflow.com Nov 14 '12 at 9:06

This question came from our site for professional and enthusiast programmers.

add comment

4 Answers 4

Instead of using -exec or xargs, you can just do:

find folder_name -not -name ".*" -delete
  • This removes all files and folders that do not start with . (hidden files/folders)
  • This removes folders if and only if they are empty (so it won't remove folders containing hidden files, as required)
share|improve this answer
add comment

That's a tricky one. An outline solution might be:

find foldername -type f ! -name '.*' -exec rm -f {} +
find foldername -type d -depth -exec rmdir {} + 2>/dev/null

The first command removes files with a name not starting with .; the second tries to remove directories. The -depth option means remove sub-directories before removing directories. The + notation is from POSIX 2008 find but works fine on Mac OS X (10.7.5, anyway). The 2>/dev/null sends any 'directory not empty' error messages (and, indeed, all others) to oblivion.

You might run into issues with symlinks, Unix sockets, FIFOs, and other non-files; tweak the first command to suit your requirements. If you use ! for history, you might need to escape that.

share|improve this answer
add comment

by passing an argument -name "*" to the find command will leave by default all the hidden files.so you can use the below command.

  find . -name "*"|xargs rm -f
share|improve this answer
1  
The rm -fr means that any directories will be forcibly removed along with all their contents, hidden and non-hidden. Using just rm -f would get rid of files and other non-directories. To remove empty directories, you need rmdir. (Using -name "*" is clever, though.) –  Jonathan Leffler Nov 14 '12 at 5:26
add comment

You could use this command:

find foldername/ -type f -not -name '.*' | xargs rm -f

The find command finds all files under foldername/ whose names don't start with a '.' (hidden file), and passes them to xargs, which runs rm -f on them.

share|improve this answer
add comment

Your Answer

 
discard

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