Home –  How to – How to delete all files of a directory in Linux?

How to delete all files of a directory in Linux?

How to delete all files of a directory in Linux?

To delete all files of a directory in Linux there are 2 methods available.

Suppose you want to delete all files of the directory dirname whose path is /home/usr/dirname then to delete all files of this directory you may use the 2 methods give below:

Method 1: Use rm command

$ rm /home/usr/dirname/*

or

$ cd /home/usr/dirname/
$rm *

Note: The above method will not delete files from sub-directories of dirname. To remove the files from sub-directories use

$ rm -r /home/usr/dirname/*

Use f option to force delete the files.

rm -rf /home/usr/dirname/*

Method 2: Use Find command

$ find /home/usr/dirname -type f -delete

or

$ cd /home/usr/dirname
$ find . -type f -delete

Note: Using the above method will delete all the files from sub-directories of dirname but it will not delete the sub-directories.

Edit: find and delete all files and folders (sub folders) [credit: ubungu]

find path_to_find -name ‘*test*’ -exec rm -rf {} \;

5 thoughts on “How to delete all files of a directory in Linux?

  1. I would suggest that before removing files, triple check to make sure you actually don’t need those files and that you are in the correct directory.

    use:

    $ pwd

    to get the exact location of where you are before trying to remove anything.

    Something else I would recommend is rename files or move them to a different directory and only when you are really sure remove those files.

    Or simply, make a back up of the file/files you are removing specially when you are using the flags -rf

    Keep it Open Source!

  2. ubungu

    find and delete all files and folders (sub folders)

    find path_to_find -name ‘*test*’ -exec rm -rf {} \;

  3. arsen

    Does it mean that sudo rm / will destroy the OS ?
    It seems that there should be a warning or a confirmation request.

    Thank you

Leave a Reply

Your email address will not be published. Required fields are marked *