How to delete all files from current directory including current directory?

末鹿安然 提交于 2019-12-06 03:02:39

问题


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.



来源:https://stackoverflow.com/questions/550922/how-to-delete-all-files-from-current-directory-including-current-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!