1

How to safely remove all files (including hidden files) from current directory (after cding to that directory)?

As far as I know, cd RELEVANT_DIR && rm * won't remove hidden files.

I would assume cd RELEVANT_DIR && rm -rf ./* is the right command but I might be wrong.

Update

I do want to remove directories (and possible symlinks and basically everything in the directory) as well.

8
  • I'm pretty sure that question has been asked before. See What's the fastest way to remove all files & subfolders in a directory? for an answer to your specific question. I'll try and find a closer duplicate. Jun 11, 2021 at 6:31
  • Have you considered using find with -delete?
    – FelixJN
    Jun 11, 2021 at 8:19
  • 1
    Why would you use rm -rf for hidden files? Do you also want to remove directories? What does "safely" mean here?
    – terdon
    Jun 11, 2021 at 8:26
  • 1
    @terdon I understood rm -rf removes everything, including directories with the possible exception of hidden files. I do want to remove directories; about safely I am not sure myself, just something conventional. Jun 11, 2021 at 9:18
  • 1
    Well, -f is as far from safe as it gets. To remove directories, you just need -r. See man find. The -f is to force remove even if the files are non-writeable by you.
    – terdon
    Jun 11, 2021 at 9:20

1 Answer 1

3

Since you've referenced rm -rf * I've assume you don't just mean that you want to delete files, but that you want to delete all content including directories.

With bash

cd "RELEVANT_DIR" && ( shopt -s dotglob; rm -r * )

Otherwise with POSIX tools

cd "RELEVANT_DIR" && (
    find . ! -type d -delete
    find . -depth -path './*' -type d -exec rmdir {} +
)

In this example omit the second find if you want to leave any directory structure intact.

2
  • Whatever method you use, try replacing rm with ls - this will give you some idea of the effect of your command. Jun 11, 2021 at 17:03
  • @JeremyBoden not quite. Consider a directory called dir. Now rm -r dir will delete dir as expected, but ls dir will list the contents of dir rather than dir itself. (Consider also that dir might be one of the values expanded from the use of *.) A better approach is to prefix the command with echo, for example here echo rm -r * May 16, 2023 at 13:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .