How to Delete Files and Folers in Linux

This command is used to remove files. It can also be used to remove directories when it’s invoked with the -r option. Alternatively, check the rmdir command.

General syntax for rm command:

$ rm [OPTION...] [FILE...]
Delete a file
rm [file]

The rm command removes a single file. To do this, type rm followed by the name of the file you want to delete.

Example: Deleting the example.txt file located in the /ExampleDir directory.

delete file
Remove files without confirmation
rm -f [file]

This option allows users to remove write-protected files without confirmation.

Example: Let’s delete the write-protected newfile.txt file.

delete file without confirmation
Delete multiple files
rm [file1] [file2] [file3]

Use the rm command with filenames as arguments to remove multiple files at once.

Example: Removing several files new1, new2, new3 located in the /NameDir directory.

delete multiple files
Display output message
rm -v [filename]

The -v (verbose) option allows you to get information about what is being removed.

Example: Deleting the example.txt file and getting information about it.

display output message
Prompt for confirmation before deleting a file
rm -i [filename]

This option is used to request confirmation before deleting a file. Typing y (yes) confirms, typing n (no) stops.

Example: When deleting the name.txt file, a confirmation message comes up. Enter y to confirm deletion.

confirmation before delete

“rmdir”

This command removes directory as well as files within the directory. There isn’t significant difference with the rm -r command except that it can not be used to remove a file.

General syntax for rmdir command:

$ rmdir [OPTION...] [DIRECTORY...]
Remove a directory
rmdir [file]

Use this command to remove a directory, but it will only be removed if it is empty.

Example: Entering the rmdir command followed by the directory name ExampleDir to remove it.

delete dir
Delete multiple directories
rmdir [file1] [file2] [file3]

This command allows you to delete several directories at once, but they all must be empty.

Example: Deleting all directories new1, new2, and new3 at the same time.

delete multiple dir
Remove parent directories
rmdir -p [directory-path]

The -p option removes the specified directory and its parent directories.

Example: Removing the directory path newdir/dir1. The command removes the newdir directory after deleting the dir1 directory.

delete parent directory
WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail