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! - rm may be the most dangerous command in Unix. Because Unix doesn't have a Trash that lets you recover mistakenly deleted files, when you delete a file, it's gone forever.
- 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.
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.
- 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! - This is the most dangerous command in all of Unix. If you enter this command in the root directory (/), you will erase the entire disk (if you have permission). Use this command with care!
- You may want to include the -i option (for example, rm -Ri *; Figure 25 ) to confirm each deletion so you do not delete files or subdirectories by mistake.
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.
- The rmdir command will result in an error message if the directory you are trying to remove is not empty (Figure 26 ).
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 ).