Search code examples
zshrm

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

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