Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 752
Ib33X Avatar asked Feb 15 '09 14:02

Ib33X


People also ask

Which command is used to delete all files in the current directory and all its?

Use the rm command to remove files you no longer need. The rm command removes the entries for a specified file, group of files, or certain select files from a list within a directory.

How do I delete all files in the current non empty directory including all its non empty sub-directories using only one command?

To remove a directory that is not empty, use the rm command with the -r option for recursive deletion. Be very careful with this command, because using the rm -r command will delete not only everything in the named directory, but also everything in its subdirectories.

How do you delete a directory and its all contents in terminal?

Delete a Directory ( rm -r ) To delete (i.e. remove) a directory and all the sub-directories and files that it contains, navigate to its parent directory, and then use the command rm -r followed by the name of the directory you want to delete (e.g. rm -r directory-name ).


2 Answers

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

like image 68
Johannes Weiss Avatar answered Sep 23 '22 02:09

Johannes Weiss


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

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

like image 37
dwc Avatar answered Sep 22 '22 02:09

dwc