Remove File/Directory

Remove a File

To remove a file or a directory you can use the rm command. Follow the below syntax to remove a file.

Syntax:

rm [Options] <file-name>

Example 1

  • To remove a file named file.txt, you simply type:

rm file.txt

Example 2

-i option can be used to ask the user for confirmation before removing each file. You have to press y to confirm the deletion, or any other key to discard deletion.

  • The previous example can be rewritten as follows:

rm -i file.txt

Output:

rm: remove regular file 'file.txt'?

Press y to confirm your selection to delete the write-protected file.

Example 3

  • Sometimes you may need to remove more than a file. This can be accomplished at once. For example, to remove file1.txt, file2.txt, and file3.txt, you can type:

rm file1.txt file2.txt file3.txt

Remove a Directory

To remove a directory from your current directory, you should use the rm command, which stands for remove.

Syntax

rm -r <DirectoryName>

Example 1

  • For example, if you would like to remove directory birds, you would type:

rm -r birds

The command recursively removes non-empty directories and all the contents in the birds directory.

Example 2

  • If a sub directory or a file in the directory is write-protected, you will be prompted to confirm the deletion. To remove a directory without being prompted, use the -f option:

rm -rf birds

Example 3

  • To remove multiple directories at once, enter the rm command followed by names of the directory separated by space.

rm -r dir1 dir2 dir3

Using rmdir Command

  • To remove a directory using the rmdir command, enter the following command point_down

rmdir birds

If the birds directory isn’t empty, then this command won’t remove the directory. You will first need to remove the contents inside the directory using the rm command or manually. Then, run rmdir birds to get rid of the directory.

The rmdir command removes a directory only if it’s empty. If any specified directory isn’t empty, rmdir won’t remove it, and will proceed to try and remove other directories you specified. To remove both a parent directory and a subdirectory of that parent, the subdirectory must be specified first. This way, the parent directory will be empty when rmdir tries to remove it.