官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 宜章县| 永仁县| 舒城县| 如东县| 甘孜县| 乳源| 嘉祥县| 温泉县| 宁海县| 收藏| 宜章县| 彭阳县| 万全县| 安顺市| 孝昌县| 中阳县| 永昌县| 怀柔区| 鲁山县| 灵武市| 松阳县| 天台县| 天长市| 苍梧县| 广元市| 鄂伦春自治旗| 孟州市| 增城市| 娄底市| 鹿泉市| 墨竹工卡县| 长顺县| 沂源县| 轮台县| 确山县| 介休市| 临澧县| 奉贤区| 潼关县| 克什克腾旗| 饶平县|