How can I delete all files in a folder, but not the folder itself, in zsh?

Viewed 132

Unfortunately zsh: how to delete contents in folder without deleting the folder? does not have any good answer.

I'm currently using rm -rf {.,}* and if that fails because there is no hidden file in the folder I do another rm -rf *. This is of course annoying, not least because I am prompted for confirmation twice (so just putting them in a row with ; wouldn't solve much.)

Is there a solution that

  • works in the presence and absence of hidden files;
  • does not delete the current folder, even temporarily;
  • prompts only once?

It must work in the current folder. If it also works for a specified folder, that's nice to have but not a must.

2 Answers

zsh has the GLOB_DOTS setting to make * match hidden files; you can enable this globally with setopt glob_dots if you want, or for a pattern with the (D) glob qualifier.

% print dir/*(D)

So to remove all files (hidden and unhidden) you can use:

% setopt glob_dots
% rm -rf dir/*

# Disable glob_dots for just this pattern:
% rm -rf dir/*(^D)

Or:

% rm -rf dir/*(D)

Unless I missed something, I believe this should do what you want.

For more information see man zshexpn (which is comprehensive, but also quite dense and not an easy read; section 5.9 of the Zsh User Guide is a more gentle introduction, and I recommend spending some time reading through all of the User Guide because there's lots of useful things in there).

You can delete the files inside a folder without deleting the actual folder by just adding * after a slash, for example:

rm -f my_folder/*

That way it will delete all files inside my_folder but not the actual folder itself. You can use the option r to recursive delete all inside the folder.

Update for one liner:

You could then use in the same command:

rm -rf my_folder/* my_folder/.*

enter image description here

Related