linux中删除文件和目录的命令: rm命令。rm是常用的命令,该命令的功能为删除一个目录中的一个或多个文件或目录,它也可以将某个目录及其下的所有文件及子目录均删除。对于链接文件,只是删除了链接,原有文件均保持不变。
使用rm的时候要特别谨慎,否则整个系统就会毁在这个命令(比如在/(根目录)下执行rm * -rf)。
删除一个目录中的一个或多个文件或目录,如果没有使用- r选项,则rm不会删除目录。如果使用 rm 来删除文件,通常仍可以将该文件恢复原状。
命令参数:
-f, --force 忽略不存在的文件,从不给出提示。
-i, --interactive 进行交互式删除
-r, -R, --recursive 指示rm将参数中列出的全部目录和子目录均递归地删除。
-v, --verbose 详细显示进行的步骤
--help 显示此帮助信息并退出
--version 输出版本信息并退出
用法:
1、删除一个文件,删除之前。系统会询问是否要删除
[root@91ctc testdir]# ls
test3.php test3.php~ test4.php testdir3
[root@91ctc testdir]# rm test3.php
rm: remove regular file `test3.php'? y
[root@91ctc testdir]# ls
test3.php~ test4.php testdir3
2、强制删除文件,系统不给提示
[root@91ctc testdir]# ls
test3.php~ test4.php testdir3
[root@91ctc testdir]# rm -f test4.php
[root@91ctc testdir]# ls
test3.php~ testdir3
3、删除时和用户交互,逐一询问,例如删除扩展名为log的日志文件:rm -i *.log。
[root@91ctc testdir]# ll
total 20
-rw-r--r-- 1 root root 5 May 3 02:17 socket1.log
-rw-r--r-- 1 root root 5 May 3 02:17 socket2.log
-rw-r--r-- 1 root root 5 May 3 02:17 socket3.log
-rw-r--r-- 1 root root 21 May 2 21:20 test3.php~
drwxr-xr-x 2 root root 4096 May 2 23:34 testdir3
[root@91ctc testdir]# rm -i *.log
rm: remove regular file `socket1.log'? y
rm: remove regular file `socket2.log'? y
rm: remove regular file `socket3.log'? y
[root@91ctc testdir]# ls
test3.php~ testdir3
4、删除目录和目录中的文件
[root@91ctc testdir]# ls
socket1.log socket4.log test3.php~
socket2.log socket_log testdir3
[root@91ctc testdir]# rm -r socket_log
rm: descend into directory `socket_log'? y
rm: remove regular file `socket_log/socket3.log'? y
rm: remove directory `socket_log'? y
[root@91ctc testdir]# ls
socket1.log socket4.log testdir3
socket2.log test3.php~
可见,有提示,是否进入目录socket_log,是否删除目录中的文件,是否删除文件,三个提示,每次提示,都要输入y才能删除,很是麻烦。
5、强制删除目录和目录中的文件,不提示用户
只需将上面例子,改成rm -rf socket_log即可。
6、定义一个回收站
下面的例子模拟了回收站的效果,即删除文件的时候只是把文件放到一个临时目录中,这样在需要的时候还可以恢复过来。
[root@91ctc testdir]# myrm(){ D=/tmp/$(date +%Y%m%d%H%M%S); mkdir -p $D; mv "$@" $D && echo "moved to $D ok"; }
[root@91ctc testdir]# ls
socket1.log socket4.log testdir3
socket2.log test3.php~
[root@91ctc testdir]# alias rm='myrm'
[root@91ctc testdir]# touch 1.log 2.log 3.log
[root@91ctc testdir]# ll
total 20
-rw-r--r-- 1 root root 0 May 3 02:29 1.log
-rw-r--r-- 1 root root 0 May 3 02:29 2.log
-rw-r--r-- 1 root root 0 May 3 02:29 3.log
-rw-r--r-- 1 root root 4 May 3 02:21 socket1.log
-rw-r--r-- 1 root root 4 May 3 02:21 socket2.log
-rw-r--r-- 1 root root 4 May 3 02:21 socket4.log
-rw-r--r-- 1 root root 21 May 2 21:20 test3.php~
drwxr-xr-x 2 root root 4096 May 2 23:34 testdir3
[root@91ctc testdir]# rm [123].log
moved to /tmp/20150503022936 ok
[root@91ctc testdir]# ll
total 20
-rw-r--r-- 1 root root 4 May 3 02:21 socket1.log
-rw-r--r-- 1 root root 4 May 3 02:21 socket2.log
-rw-r--r-- 1 root root 4 May 3 02:21 socket4.log
-rw-r--r-- 1 root root 21 May 2 21:20 test3.php~
drwxr-xr-x 2 root root 4096 May 2 23:34 testdir3
[root@91ctc testdir]# ls /tmp/20150503022936
1.log 2.log 3.log