Removing Files & Directories with rm & rmdir Unix includes two commands that you can use to delete files and directories: rm (remove) and rmdir (remove directory). Warning! Tips There are two options that you may want to use with the rm command: -i tells the rm command to ask permission before deleting each file (Figure 24). You must press and then at each prompt to delete the file. This is especially useful when using the rm command with wildcard characters, since it can help prevent files from being accidentally deleted. Figure 24. The rm command in action, with and without the -i option.
-R, which stands for recursively, tells the rm command to delete everything within a directory, including its sub-directories and their contents. The -R option can be very dangerous; you may want to use it in conjunction with the -i option to confirm each deletion.
The rm command's file operand can be a file or a directory name. If you are deleting a non-empty directory, you must use the -R (recursive) option. You can learn more about the rm and rmdir commands and their options on their man pages. Type man rm or man rmdir and press to view each command's man pages.
To remove a file Type rm file ... and press . For example, rm file1 removes the file named file1 from the current directory (Figure 24). To remove files using a wildcard character Type rm followed by the wildcard search string and press . For example, rm *.bak removes all files ending with .bak from the current directory. To remove all files in a directory Type rm * and press (Figure 25). Figure 25. Two more examples of the rm command. In the first, the rm * command string deletes all files in the directory, but not the subdirectory named dir30. In the second, the -Ri options delete all contents with confirmation; the only item still in the directory is the subdirectory named dir30. Tips You may want to include the -i option (for example, rm -i *) to confirm each deletion so you do not delete files by mistake. Since the rm command cannot remove directories without the -R option, an error message may appear when you use the rm * command string in a directory that contains subdirectories (Figure 25). To remove all files & subdirectories in a directory Type rm -R * and press (Figure 25). Warning! Tip To remove an empty directory Type rmdir directory … and press . For example, rmdir Originals removes the subdirectory named Originals in the current directory (Figure 26). Figure 26. This example shows two attempts to delete a subdirectory. The first, using the rmdir command, is not successful because the directory is not empty. The second, using the rm -R command string, does the job.
Tip To remove a directory & its contents Type rm -R directory and press . For example, rm -R Originals removes the directory named Originals even if it is not empty (Figure 26). |