To delete a directory in Linux in a desktop environment is easy as pressing the Del / Delete key.

To delete a directory in Linux using command line CLI in Terminal or SSH you can use the rm command.

The bellow works fine for a file.

rm /dirname/filename 

A directory cannot be removed just like that.

The rm command needs to be set to recursive mode.

It will delete all contents of the directory if any and delete the directory itself.

rm command

You have to specify the recursive option for directories otherwise you get the error when you try to use rm without -R or -r to delete a directory.

rm options

  -f, --force           ignore nonexistent files and arguments, never prompt
  -i                    prompt before every removal
  -I                    prompt once before removing more than three files, or
                          when removing recursively; less intrusive than -i,
                          while still giving protection against most mistakes
      --interactive[=WHEN]  prompt according to WHEN: never, once (-I), or
                          always (-i); without WHEN, prompt always
      --one-file-system  when removing a hierarchy recursively, skip any
                          directory that is on a file system different from
                          that of the corresponding command line argument
      --no-preserve-root  do not treat '/' specially
      --preserve-root[=all]  do not remove '/' (default);
                              with 'all', reject any command line argument
                              on a separate device from its parent
  -r, -R, --recursive   remove directories and their contents recursively
  -d, --dir             remove empty directories
  -v, --verbose         explain what is being done
      --help     display this help and exit
      --version  output version information and exit

rm -R directory commands

Commands

[dragos@localhost ~]$ ls
[dragos@localhost ~]$ mkdir diy.rednumberone.com
[dragos@localhost ~]$ ls
diy.rednumberone.com
[dragos@localhost ~]$ touch diy.rednumberone.com/testfile1
[dragos@localhost ~]$ ls
diy.rednumberone.com
[dragos@localhost ~]$ ls diy.rednumberone.com/
testfile1
[dragos@localhost ~]$ rm diy.rednumberone.com/testfile1
[dragos@localhost ~]$ ls diy.rednumberone.com/
[dragos@localhost ~]$ touch diy.rednumberone.com/testfile2
[dragos@localhost ~]$ ls diy.rednumberone.com/
testfile2
[dragos@localhost ~]$ rm diy.rednumberone.com/
rm: cannot remove 'diy.rednumberone.com/': Is a directory
[dragos@localhost ~]$ rm -R diy.rednumberone.com/
[dragos@localhost ~]$ ls
[dragos@localhost ~]$


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.