rm -rf all files and all hidden files without . & .. error

  • rm -rf /some/path/* deletes all non-hidden files in that dir (and subdirs).

    rm -rf /some/path/.* deletes all hidden files in that dir (but not subdirs) and also gives the following error/warning:

    rm: cannot remove directory: `/some/dir/.'
    rm: cannot remove directory: `/some/dir/..'

    What is the proper way to remove all hidden and non-hidden files and folders recursively in a target directory without receiving the warning/error about . and ..?

  • evilsoup

    evilsoup Correct answer

    7 years ago

    You could always send error messages to /dev/null

    rm -rf /some/path/.* 2> /dev/null

    You could also just

    rm -rf /some/path/
    mkdir /some/path/

    ...then you won't have to bother with hidden files in the first place.

    But what if I only want to delete the hidden files?

    @CMCDragonkai that should be a different question, but you can find the solution in Gilles' answer (`rm ..?* .[!.]*` should do it).

    Doesn't deleting and recreating the directory pose the risk that the file permissions are not right afterwards (especially important in server environments). Who could one create the folder with the same permissions as before automatically?

    @YoLudke You are absolutely correct, in many situations it doesn't matter but deleting the folder and recreating is not semantically equivalent to emptying that folder; so be careful doing that!

    Deleting the directory is not always possible. In my case the directory is a docker volume, and while i can do whatever I want inside the volume, i cant change the volume itself from within the container.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM