Remove files and directories using the RM command in Linux

Home > Search > Linux commands
  by

The rm command can be used to remove files and directories. Let's take an example where there is a file named file1 at /home/john.doe.

[john.doe@server1 ~]# ls -l
-rw-rw-r--.  1  john.doe  john.doe  183  May 23 18:53  file1

 

The rm command followed by the file name can be used to remove the file. In this example, file1 is removed, and file1 no longer resides in the /home/john.doe directory.

[john.doe@server1 ~]# rm file1
[john.doe@server1 ~]# ls -l

 


Remove another users file

By default, you can remove files you own, and you cannot remove files you do not own. For example, if jane.doe attempts to remove file1, which is owned by john.doe, an error will appear.

[jane.doe@server1 ~]# rm /home/john.doe/file1
rm: cannot remove '/home/john.doe/file1': Permission denied

 

If jane.doe is a member of the sudo group, jane.doe can remove file1 using the sudo command.

[jane.doe@server1 ~]# sudo rm /home/john.doe/file1

 

Root can remove any file without having to use sudo.

[root@server1 ~]# rm /home/john.doe/file1

 


Remove directories

Let's say there is a directory named bin in the /home/john.doe directory.

[john.doe@server1 ~]# ls -l
drwxrwxr-x.  2  john.doe  john.doe  6  May 23 19:06  bin

 

The rm command without any options will display an error when attempting to remove the bin directory.

[john.doe@server1 ~]# rm /home/john.doe/bin
rm: cannot remove '/home/john.doe/bin': Is a directory

 

The -r, -R, or --recursive option can be used to remove directories that are not empty. This will also remove all of the contents inside of the directory.

[john.doe@server1 ~]# rm -r /home/john.doe/bin

 

The -d or --dir option can be used to remove a directory that is empty.

[john.doe@server1 ~]# rm -d /home/john.doe/bin

 


Prompt before removal

To ebb on the side of caution, the -i or -I options can be used to display a prompt before removing a file.

[john.doe@server1 ~]# rm -i /home/john.doe/file1
rm: remove regular file 'file1'?

 

The -i option will prompt for every file being removed. For example, let's say the /home/john.doe directory contains 5 files.

[john.doe@server1 ~]# rm -i /home/john.doe/*
rm: remove regular file 'file1'?
rm: remove regular file 'file2'?
rm: remove regular file 'file3'?
rm: remove regular file 'file4'?
rm: remove regular file 'file5'?

 

The -I option will only prompt once for every file being removed.

[john.doe@server1 ~]# rm -I /home/john.doe/*
rm: remove 5 arguments?

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments