Deleting or Removing Directories and Files

This entry is part 5 of 6 in the series Beginner Linux Administrator

Now that we know how to create directories and files, we need to learn how to delete them.

There are two commands for deleting or removing directories in linux. The command “rmdir” and “rm”.
The “rmdir” and “rm” commands are unforgiving and there is no undelete. Kinda scary to think that once you delete something its gone.

The command to delete empty directories

NAME
rmdir – remove empty directories

SYNOPSIS
rmdir [OPTION]… DIRECTORY…

The “rmdir” can only be used on directories that do not have any contents.

Lets delete the directory “directory2″:

$ rmdir directory2

Lets now check to see if the directory “directory2″ was deleted:

directory5  file1  file1.text  file1.txt.bak  file1.txt.org  level1  subdir1

Lets now try an delete a non-empty directory using “rmdir”:

$ rmdir subdir1
rmdir: failed to remove `subdir1': Directory not empty

We delete non empty directories by using the “rm” command

The command to delete

NAME
rm – remove files or directories

SYNOPSIS
rm [OPTION]… FILE…

Lets try and delete a non empty directory with the “rm” command:

$ rm subdir1
rm: cannot remove `subdir1': Is a directory

To delete a non empty directory we use the “rm” command with the “-r” option for recursive or “remove directories and their contents recursively”

$ rm -r subdir1

Lets see if directory “subdir1″ and all of its contents and sub directories were removed:

$ ls
directory5  file1  file1.text  file1.txt.bak  file1.txt.org  level1

To delete files we use the “rm” command.

Lets delete the file “file1.txt”:

$ rm file1.txt

Lets see if “file1.txt” got deleted:

$ ls
directory5  file1  file1.txt.bak  file1.txt.org  level1

Just like with mkdir and touch, you can delete more then one directory or file by listing them them separated by a space.

$ rmdir dir1 dir2 dir3
$ rm -r dir1 dir2 dir3
$ rm file1 file2 file3

Now that you know how to create, rename, move, and delete directories and files. Have some fun and play around with all the commands you just learned.

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
Fabio Milano has written 70 articles for us. Fabio Milano is a certified RHCE, MCP, and CFOI. He runs an IT consulting and services company called RDS Support inc. Website:http://www.rdssupport.com

No Comments

Leave a reply