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

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.

主站蜘蛛池模板: 梁河县| 大英县| 潍坊市| 漳平市| 万山特区| 新源县| 甘德县| 迁安市| 新宾| 达日县| 威远县| 集贤县| 泰安市| 东明县| 塘沽区| 衡东县| 静乐县| 六枝特区| 永善县| 荥阳市| 阿坝县| 德惠市| 喀什市| 双辽市| 江孜县| 林西县| 宜都市| 西和县| 高淳县| 梧州市| 长泰县| 德庆县| 和静县| 贡山| 莒南县| 龙海市| 长顺县| 象州县| 宁南县| 独山县| 洛阳市|