Learn Linux Quickly
上QQ阅读APP看书,第一时间看更新

Removing directories

You can pass the recursive -r option to the rm command to remove directories. To demonstrate, let’s first create a directory named garbage in Elliot's home directory:

elliot@ubuntu-linux:~$ mkdir garbage
elliot@ubuntu-linux:~$ ls
Desktop dir1 garbage small

Now let's try to remove the garbage directory:

elliot@ubuntu-linux:~$ rm garbage
rm: cannot remove 'garbage': Is a directory
elliot@ubuntu-linux:~$

Shoot! I got an error because I didn't pass the recursive -r option. I will pass the recursive option this time:

elliot@ubuntu-linux:~$ rm -r garbage
elliot@ubuntu-linux:~$ ls
Desktop dir1 small

Cool! We got rid of the garbage directory.

You can also use the rmdir command to remove only empty directories. To demonstrate, let’s create a new directory named garbage2 and inside it, create a file named old:

elliot@ubuntu-linux:~$ mkdir garbage2
elliot@ubuntu-linux:~$ cd garbage2
elliot@ubuntu-linux:~/garbage2$ touch old

Now let's go back to Elliot's home directory and attempt to remove garbage2 with the rmdir command:

elliot@ubuntu-linux:~/garbage2$ cd ..
elliot@ubuntu-linux:~$ rmdir garbage2
rmdir: failed to remove 'garbage2': Directory not empty

As you can see, it wouldn’t allow you to remove a nonempty directory. Therefore, let's delete the file old that’s inside garbage2 and then reattempt to remove garbage2:

elliot@ubuntu-linux:~$ rm garbage2/old
elliot@ubuntu-linux:~$ rmdir garbage2
elliot@ubuntu-linux:~$ ls
Desktop dir1 small
elliot@ubuntu-linux:~$

Boom! The garbage2 directory is gone forever. One thing to remember here is that the rm -r command will remove any directory (both empty and nonempty). On the other hand, the rmdir command will only delete empty directories.

For the final example in this chapter, let's create a directory named garbage3, then create two files a1.txt and a2.txt inside it:

elliot@ubuntu-linux:~$ mkdir garbage3
elliot@ubuntu-linux:~$ cd garbage3/
elliot@ubuntu-linux:~/garbage3$ touch a1.txt a2.txt
elliot@ubuntu-linux:~/garbage3$ ls
a1.txt a2.txt

Now let's get back to Elliot's home directory and attempt to remove garbage3:

elliot@ubuntu-linux:~/garbage3$ cd ..
elliot@ubuntu-linux:~$ rmdir garbage3
rmdir: failed to remove 'garbage3': Directory not empty
elliot@ubuntu-linux:~$ rm -r garbage3
elliot@ubuntu-linux:~$ ls
Desktop dir1 Downloads Pictures small
elliot@ubuntu-linux:~$

As you can see, the rmdir command has failed to remove the nonempty directory garbage3, while the rm -r command has successfully removed it.

Nothing makes information stick in your head like a good knowledge-check exercise.