How to use rm and rmdir utilities to remove or delete files and directories in Linux

Introduction:

Use sudo with rm command for those files which are having root user and group permissions or if getting message  Access Denied.

Sudo rm text2.txt

rm text.txt

1

How to delete a files and directory in linux

In Linux operating system if needs to delete directory use following commands:

  • rmdir command – removes empty directories/folders

  • rm command – removes a directory/folder along with all the files and sub-directories in it.

How to remove or delete a files in linux based O.S.

The rm utility is used to delete files in a Linux. 

To delete a single file use below command.

rm file

The rm command can be used to delete more than one file at a time:

rm file_1 file_2 file_3

Wildcards can be used with this command.

For example, to delete all files with the .txt filename then:

rm *.txt

This method is also used to delete all files that contain a string of characters:

rm *text*.*

This will erase any file that has the word text in the name. The system will search the current directory for the file you want to remove. To delete a file in a different directory then switch to that:

cd /11 rm file1

rm text.txt

Or you can specify the file location in a single command directly:

rm /tmp/text.txt

Note: once the rm command execute then files or folder won’t be able to restore.

rm Command Options

If deleting multiple files add a confirmation prompt. Use the ioption to use an interactive dialog:

rm –i *.txt

Confirm the deletion of files by typing ‘yes’ or ‘no.’

2

To display the progress of the deletion with the v or verbose command:

rm –v *.txt

The output confirms that the file test.txt has been successfully removed.

To forcefully removal of file which is write-protected then use f for forcefully remove the file.

rm –f filename

Use sudo with rm command to delete file which is having Access denied.

sudo rm filename

How to remove a directory in linux Opearting system using Command line

By adding -r (-R) parameter with rm command to delete folder with files recursively.

To remove a directory with all files use option as below:

rm –r directory-name

rmdir directory-name

This will prompt confirmation before deleting.

To remove a directory without want to be an any confirmation:

rm –rf directory

Also can delete more than one directory or folder at a time:

rm –r directory_name1 directory_name2 directory_name3

rmdir directory_name1 directory_name2 directory_name3

 

In this blog we have learn how to delete files and directories in Linux. The rm and rmdir commands are flexible with multiple options. 

 

Leave a Reply