In BASH you can use the trailing slash (I think it should work in any POSIX shell):
rm -R -- */
Note the --
which separates options from arguments and allows one to remove entries starting with a hyphen - otherwise after expansion by the shell the entry name would be interpreted as an option by rm
(the same holds for many other command line utilities).
Add the -f
option if you don't want to be prompted for confirmation when deleting non-writeable files.
Note that by default, hidden directories (those whose name starts with .
) will be left alone.
An important caveat: the expansion of */
will also include symlinks that eventually resolve to files of type directory. And depending on the rm
implementation, rm -R -- thelink/
will either just delete the symlink, or (in most of them) delete the content of the linked directory recursively but not that directory itself nor the symlink.
If using zsh
, a better approach would be to use a glob qualifier to select files of type directory only:
rm -R -- *(/) # or *(D/) to include hidden ones
or:
rm -R -- *(-/)
to include symlinks to directories (but because, this time, the expansion doesn't have trailing /
s, it's the symlink only that is removed with all rm
implementations).
With bash
, AT&T ksh
, yash
or zsh
you can do:
set -- */
rm -R -- "${@%/}"
to strip the trailing /
.
With the file zz containing the list of file names, this works, so just replace cat zz.
cat zz | grep -vF -f <(cat zz|sort -r|uniq -w11)
e.g.
echo *.sql | grep -vF -f <( echo *.sql | sort -r | uniq -w11 ) | xargs rm
As is, it won't work if spaces in file names, and very fragile to filename length.
Best Answer
By default
bash
doesn't glob dot-files, so to remove everything but hidden files inbash
, usingrm
:Sample output:
To remove everything but
.gitkeep
inbash
, enabling globbing for dot-files and usingrm
:Sample output: