Search code examples
bashfile-iocommand-linedelete-directory

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?


Solution

  • 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