rm -fr *
不會刪除.files
如何rm -fr *可靠?
在另一方面,
rm -fr * .*
將刪除太多了!
有一種可靠的方法遞歸刪除Bash中的目錄的所有內容?我能想到的
一種方法是:
rm -fr $PWD
mkdir $PWD
cd $PWD
這有刪除$PWD
暫時的副作用。
rm -fr *
不會刪除.files
如何rm -fr *可靠?
在另一方面,
rm -fr * .*
將刪除太多了!
有一種可靠的方法遞歸刪除Bash中的目錄的所有內容?我能想到的
一種方法是:
rm -fr $PWD
mkdir $PWD
cd $PWD
這有刪除$PWD
暫時的副作用。
我建議首先使用:
shopt -s dotglob
dotglob
:如果設置,bash的包括文件名與路徑擴展的結果
rm -fr * .*
一個.
開始是相對「安全」。 POSIX禁止rm
採取行動.
和..
。
rm -rf . ..
將是一個空操作,但它會返回1.如果你不希望錯誤的回報,你可以這樣做:
rm -rf .[!.]*
這是POSIX標準,無需擴展的bash 。
您還可以使用發現:
find . -delete
你可以使用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.
的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 ..?*
我們需要避免包含星號的參數來解決此問題。
'rm -rf dir'很好,因爲long dir不是當前的工作目錄。 – codeforester
爲了將來的參考,這將更適合[unix.stackexchange.com](http://stackoverflow.com/q/16926130/25507)。 –