How to delete all files from current directory inc

2019-04-08 20:21发布

问题:

How can I delete all files and subdirectories from current directory including current directory?

回答1:

Under bash with GNU tools, I would do it like that (should be secure in most cases):

rm -rf -- "$(pwd -P)" && cd ..

not under bash and without GNU tools, I would use:

TMP=`pwd -P` && cd "`dirname $TMP`" && rm -rf "./`basename $TMP`" && unset TMP

why this more secure:

  • end the argument list with -- in cases our directory starts with a dash (non-bash: ./ before the filename)
  • pwd -P not just pwd in cases where we are not in a real directory but in a symlink pointing to it.
  • "s around the argument in cases the directory contains spaces

some random info (bash version):

  • the cd .. at the end can be omitted, but you would be in a non-existant directory otherwise...

EDIT: As kmkaplan noted, the -- thing is not necessary, as pwd returns the complete path name which always starts with / on UNIX



回答2:

olddir=`pwd` && cd .. && rm -rf "$olddir"

The cd .. is needed, otherwise it will fail since you can't remove the current directory.



回答3:

rm -fr "`pwd`"


回答4:

I think this would be possible under DOS / Windows CMD, but I can't quite find a way to pipe the data between commands. Someone else may know the fix for that?

FOR /F %i IN ('cd') DO SET MyDir=%i | CD .. | RD /S %MyDir%


回答5:

operating system? on the *NIX-based stuff, you're looking for 'rm -rf directory/'

NOTE: the '-r' flag for 'recursive' can be dangerous!



回答6:

You just can go back the target folder's parent folder, then use 'rm -rf yourFolder'. or you can use 'rm -rf *' to delete all files and subfolders from the current folder.