---
title: "我使用过的Linux命令之rm - 删除文件或目录，当心系统毁灭"
author: "codingstandards"
date: "2011-04-01T21:56:07Z"
tags: ["F#", "HTML", "ITeye", "Linux", "OS"]
categories: ["操作系统"]
slug: "linux-rm"
draft: false
lastmod: "2011-04-01T21:59:24Z"
id: 983531
url: "https://codingstandards.iteye.com/blog/983531"
---

# 我使用过的Linux命令之rm - 删除文件或目录

本文链接：[http://codingstandards.iteye.com/blog/983531](/blog/983531)   （转载请注明出处）

 

## 用途说明

rm命令是常用的命令，用来删除文件或目录（remove files or directories）。它也是一个危险的命令，使用的时候要特别当心，尤其对于新手，否则整个系统就会毁在这个命令（比如在/下执行rm * -rf）。所以，我们在执行rm之前最好先确认一下在哪个目录，到底要删除什么东西，操作时保持清醒的头脑。

在rm的手册中写道：用rm删除文件还是有可能恢复文件内容的，如果要不可恢复的删除文件，考虑使用shred命令。（\_Warning\_: If you use \`rm' to remove a file, it is usually possible to recover the contents of that file.  If you want more assurance that the contents are truly unrecoverable, consider using \`shred'.）至于具体怎么恢复rm删除的文件，有文章专门讨论了。但是不幸的是文件系统是ext2可恢复、ext3不可恢复，ext3的删除机制是直接把 inode data 删除了，所以造成 ext3 无法反删除(ext3设计为无法恢复被删除的文件)。不过，有些文章提到可以使用debugfs工具来尝试恢复。无论如何，rm文件之后要想恢复还是很麻烦的。

为了避免一个命令毁掉整个系统、或者误删重要文件（ 比如辛苦编写的源程序文件），最好的方式不去删除，而是采用改名或者移动文件位置来去掉不需要的文件（mv命令）。还有就是，在进行一些关键操作时，先对数据进行备份，尤其是异机备份、异地备份。

 

## 常用参数

格式：rm file

删除文件file，系统会先询问是否删除。

 

格式：rm -f file

强行删除file，系统不再提示。

 

格式：rm -rf dir

强行删除目录dir下的所有文件、子目录下的所有文件和目录、删除dir本身。

 

格式：rm -f \*.LOG*

删除日志文件。

 

## 使用示例

### 示例一 rm的真实身份

\[root@jfht ~]# type -a rm  
rm is aliased to \`rm -i'  
rm is /bin/rm  
\[root@jfht ~]#

 

### 示例二 回收站尝试

下面的操作过程模拟了回收站的效果，即删除文件的时候只是把文件放到一个临时目录中，这样在需要的时候还可以恢复过来。

\[root@jfht ~]# myrm(){ D=/tmp/$(date +%Y%m%d%H%M%S); mkdir -p $D; mv "$@" $D && echo "moved to $D ok"; }  
\[root@jfht ~]# alias rm='myrm'  
\[root@jfht ~]# touch 1.txt 2.txt 3.txt  
\[root@jfht ~]# ls \[123].txt            
1.txt  2.txt  3.txt  
\[root@jfht ~]# rm \[123].txt  
moved to /tmp/20110401214056 ok  
\[root@jfht ~]# ls /tmp/20110401214056/  
1.txt  2.txt  3.txt  
\[root@jfht ~]#

 

### 示例三 删除以-开头的文件

\[root@jfht ~]# touch -- -f  
\[root@jfht ~]# ls -- -f  
\-f  
\[root@jfht ~]# rm -- -f  
moved to /tmp/20110401214709 ok

也可以使用下面的操作步骤。

\[root@jfht ~]# touch ./-f  
\[root@jfht ~]# ls ./-f  
./-f  
\[root@jfht ~]# rm ./-f  
moved to /tmp/20110401214859 ok  
\[root@jfht ~]#

 

## 问题思考

## 相关资料

【1】Linux宝库 Linux指令篇:档案目录管理--rm  
http://doc.linuxpk.com/206.html  
【2】Linux公社 Linux下用rm删除的文件的恢复方法  
http://www.linuxidc.com/Linux/2008-08/14744.htm  
【3】maxpassion的个人空间 Linux恢复误删除文件（转载）  
http://www.cnttr.com/49230/viewspace\_6093.html  
【4】52CTO Linux ext3文件系统 rm恢复  
http://os.51cto.com/art/200908/141407.htm

 

返回 [我使用过的Linux命令系列总目录](/blog/786653)