How to remove a file in linux ?

rm is one of the basic commands used to remove a file in linux. rm can be used to remove a file, directory, device nodes, links and so on.The rm syntax is given below


rm file
rm /path/to/file
rm /path/to/directory

Some important options

  • -r (recursive) : remove the contents recursively
  • -i (interactive) : prompt before removing
  • -f (force) : never prompts and ignore non-existent files
  • -v (verbose) : explains what is being done.

 

Examples


To remove a file abc.txt, type
rm abc.txt

To remove a directory the directory should be empty or the contents need to be removed recursively. For that we use rm with -r option to remove a directory named Misc located in /home/calypso/, type

rm -r /home/calypso/Misc
To understand how rm works on a directory, imagine the directory Misc has the following structure

Misc/
├── abc.txt
├── document
│   └── doc.txt
├── list.csv
└── README.txt

In the above directory structure the directory Misc contains the files abc.txt, doc.txt, README.txt and a sub-directory named document. Inside the sub-directory there is again a file named doc.txt. So total there are 4 files and 1 directory. To remove the directory Misc and view what is happening, type

rm -rv /home/calypso/Misc
Sample Output:
removed `/home/calypso/Misc/README.txt'
removed `/home/calypso/Misc/abc.txt'
removed `/home/calypso/Misc/list.csv'
removed `/home/calypso/Misc/document/doc.txt'
removed directory: `/home/calypso/Misc/document'
removed directory: `/home/calypso/Misc'

rm should be used with high caution, especially when you are logged in as the root user. No matter who you are, any careless usage of rm command can change you from hero to zero within few second. You should never ever try run commands like rm - rf / as a root user. This will remove all the  files from your computer. If you have any doubt use rm with -i option.

rm -i abc.txt
Sample Output:
rm: remove regular file `abc.txt'?
In the above case pressing 'y' will remove the file and pressing 'n' will keep the file.

After you remove a file with rm there is no simple method you can recover the files, i.e there is no provision to recover the files from a Trash or a Recycle Bin. So be careful while using. 

For more details see the man pages 

Comments

Popular posts from this blog

Understanding awk command with examples

Understanding sed command with example -Part 1

How to install a Software in Linux