Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 Nov 14 '12 at 9:06

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

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

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

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

  find . -name "*"|xargs rm -f
share|improve this answer
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

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

You must log in to answer this question.