The rm and rmdir commands

The rm tool deletes files, and directories if specified. Because it involves data loss by definition, shell script programmers should be very careful with this command:

$ ls
file1  file2  file3
$ rm file1 file2
$ ls
file3

Note that by default, rm does not remove directories:

$ mkdir mydir
$ rm mydir
rm: cannot remove 'mydir': Is a directory

You can force this with the standard -R or -r option, but it's safer to use rmdir. This is because rmdir will refuse to delete a directory if it still has files in it; it only deletes empty directories:

$ mkdir test1 test2
$ touch test1/file test2/file
$ rm -r test1
$ rmdir test2
rmdir: failed to remove 'test2': Directory not empty

We recommend you avoid the -R or -r flag where you can, and instead select files for deletion one by one. As a general rule of thumb in shell scripts, you should delete as little as possible, and as specifically as possible. If you carefully define what you're deleting and under what circumstances, you reduce the risk of unexpected problems. Emptying a directory manually of the files you expect to be there with rm first, and then attem

pting to clear it with rmdir, is a safe approach.

We'll learn more approaches to safely managing and d

eleting files in hierarchies in Chapter 8, Best Practices.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.90.148