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

  • Learn Linux Quickly
  • Ahmed AlKabary
  • 362字
  • 2021-06-11 18:43:50

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.

主站蜘蛛池模板: 庄河市| 陇南市| 海晏县| 通化市| 彩票| 唐山市| 太原市| 江达县| 阿拉善左旗| 延寿县| 贞丰县| 黄山市| 郁南县| 永昌县| 康乐县| 上思县| 巧家县| 东莞市| 麟游县| 蒲江县| 大丰市| 镇安县| 长顺县| 波密县| 揭西县| 乌兰浩特市| 太谷县| 正安县| 息烽县| 石屏县| 固原市| 龙海市| 深水埗区| 邳州市| 陆丰市| 鱼台县| 新巴尔虎左旗| 佛学| 全州县| 曲松县| 兴城市|