2017-03-25 66 views
2
rm -fr * 

不會刪除.files如何rm -fr *可靠?

在另一方面,

rm -fr * .* 

將刪除太多了!

有一種可靠的方法遞歸刪除Bash中的目錄的所有內容?我能想到的

一種方法是:

rm -fr $PWD 
mkdir $PWD 
cd $PWD 

這有刪除$PWD暫時的副作用。

+0

'rm -rf dir'很好,因爲long dir不是當前的工作目錄。 – codeforester

+0

爲了將來的參考,這將更適合[unix.stackexchange.com](http://stackoverflow.com/q/16926130/25507)。 –

回答

5

我建議首先使用:

shopt -s dotglob 

dotglob:如果設置,bash的包括文件名與路徑擴展的結果

1
rm -fr * .* 

一個.開始是相對「安全」。 POSIX禁止rm採取行動...

rm -rf . .. 

將是一個空操作,但它會返回1.如果你不希望錯誤的回報,你可以這樣做:

rm -rf .[!.]* 

這是POSIX標準,無需擴展的bash 。

您還可以使用發現:

find . -delete 
1

你可以使用find-delete-maxdepth

find . -name "*" -delete -maxdepth 2 

所以我們可以說你是在目錄temp看起來像這樣:

./temp 
    |_____dir1 
    |  |_____subdir1 
    X|_file X|_file  |_file 
    | 
    X|_____dir2 
      X|_file 

看着使用上面的命令將會刪除旁邊有X的文件和目錄。 subdir1不會被刪除,因爲查找將刪除文件的最大深度設置爲2,並且其中存在一個文件。 find將刪除以.開頭的文件 - 但是,它不適用於符號鏈接。

-delete 
     Delete found files and/or directories. Always returns true. 
     This executes from the current working directory as find recurses 
     down the tree. It will not attempt to delete a filename with a 
     ``/'' character in its pathname relative to ``.'' for security 
     reasons. Depth-first traversal processing is implied by this 
     option. Following symlinks is incompatible with this option. 
1

的Unix常用的智慧是使用類似:

rm -rf * .[!.]* ..?* 

,將列出以點甚至雙點開始的所有文件(不包括普通雙點(./..)。

但是如果不存在該類型的文件,那麼通配符擴展將保留星號

讓我們來測試:

$ mkdir temp5; cd temp5 
$ touch {,.,..}{aa,bb,cc} 
$ echo $(find .) 
. ./aa ./cc ./..bb ./..aa ./.cc ./.bb ./..cc ./.aa ./bb 

而且,正如所指出的,這將包括所有文件:

$ echo * .[!.]* ..?* 
aa bb cc .aa .bb .cc ..aa ..bb ..cc 

但是,如果類型中的一個不存在,星號將留:

$ rm ..?* 
$ echo * .[!.]* ..?* 
aa bb cc .aa .bb .cc ..?* 

我們需要避免包含星號的參數來解決此問題。