
rm - remove files and directories
rm command
rm command is one of the basic commands in Unix/Linux operating systems. It’s a fundamental tool for removing (deleting) files and directories.
Remove a file with rm
Simplest form of this command is rm <FILENAME>
(<FILENAME>
is a parameter - you replace it with the filename you want to remove). So if we have a file called try1
:
{% highlight command %} greys@xps:~ $ ls -al try1 try2 try3 -rw-r–r– 1 greys greys 0 Jun 5 00:22 try1 -rw-r–r– 1 greys greys 0 Jun 5 00:22 try2 -rw-r–r– 1 greys greys 0 Jun 5 00:22 try3 {% endhighlight %}
we’ll remove like this:
{% highlight command %} greys@xps:~ $ rm try1 {% endhighlight %}
and this ls
command proves that the try1
file is really gone:
{% highlight command %} greys@xps:~ $ ls -la try1 ls: cannot access ’try1’: No such file or directory {% endhighlight %}
Remove multiple files with rm
Removing multiple files is done by either listing the files as separate command line parameters to rm:
{% highlight command %} greys@xps:~ $ rm try2 try3 {% endhighlight %}
or just using a filename mask:
{% highlight command %} greys@xps:~ $ rm try* {% endhighlight %}
Remove an empty directory with rm
Although you can use rmdir command for deleting directories, it’s possible (and possibly easier) to use rm -d <DIRNAME>
command instead.
Let’s create a couple of directories with files for our next two experiments.
{% highlight command %} greys@xps:~ $ mkdir dir1 greys@xps:~ $ mkdir dir2 greys@xps:~ $ touch dir1/file1 greys@xps:~ $ touch dir2/file1 greys@xps:~ $ touch dir2/file2 greys@xps:~ $ touch dir2/file3 greys@xps:~ $ ls -al dir* dir1: total 0 drwxr-xr-x 1 greys greys 10 Jun 5 00:27 . drwxr-xr-x 1 greys greys 1670 Jun 5 00:27 .. -rw-r–r– 1 greys greys 0 Jun 5 00:27 file1
dir2: total 0 drwxr-xr-x 1 greys greys 30 Jun 5 00:27 . drwxr-xr-x 1 greys greys 1670 Jun 5 00:27 .. -rw-r–r– 1 greys greys 0 Jun 5 00:27 file1 -rw-r–r– 1 greys greys 0 Jun 5 00:27 file2 -rw-r–r– 1 greys greys 0 Jun 5 00:27 file3 {% endhighlight %}
Now if we just try to remove the dir1 directory with rm, it won’t let us:
{% highlight command %} greys@xps:~ $ rm -d dir1 rm: cannot remove ‘dir1’: Directory not empty {% endhighlight %}
… that’s because we have to remove the files inside dir1 first:
{% highlight command %} greys@xps:~ $ rm dir1/file1 {% endhighlight %}
…now let’s try removing the dir1 again, and it works just fine:
{% highlight command %} greys@xps:~ $ ls -ald dir1 ls: cannot access ‘dir1’: No such file or directory {% endhighlight %}
Use rm to remove a directory with all the files in it
We also have dir2 directory with files file2 and file3 in it from earlier, so let’s try removing it. This time though, we’ll use the rm with -r option to force rm command into deleting all the files in the dir2 recursively (and all the subdirectories if there are any):
{% highlight command %} greys@xps:~ $ rm -dr dir2 greys@xps:~ $ ls -ald dir2 ls: cannot access ‘dir2’: No such file or directory {% endhighlight %}