Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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.

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading