删除包含数千个文件的大型目录的最佳和最快方法是什么(在ubuntu中)

ite*_*kov 6 linux bash

我知道命令就像

find <dir> -type f -exec rm {} \;
Run Code Online (Sandbox Code Playgroud)

不是删除大量文件的最佳变体(总文件,包括子文件夹).它的工作原理很好,如果你有文件量小,但如果你有在子文件夹10+ MLNS文件,它可以挂一台服务器.

有谁知道任何具体的linux命令来解决这个问题?

Igo*_*bin 7

这可能看起来很奇怪但是:

$ rm -rf <dir>
Run Code Online (Sandbox Code Playgroud)

  • 在这一点上,有人应该告诉你要小心.`-f`选项强制删除没有提示 - 在错误的地方执行此操作可能会对您的系统造成严重破坏...在服务器上执行它之前测试它并习惯命令. (2认同)

Rod*_*uis 5

这是一个示例bash脚本:

#!/bin/bash

local LOCKFILE=/tmp/rmHugeNumberOfFiles.lock

# this process gets ultra-low priority
ionice -c2 -n7 -p $$ > /dev/null
if [ $? ]; then
    echo "Could not set disk IO priority. Exiting..."
    exit
fi
renice +19 -p $$ > /dev/null
if [ $? ]; then
    echo "Could not renice process. Exiting..."
    exit
fi

# check if there's an instance running already. If so--exit
if [ -e ${LOCKFILE} ] && kill -0 `cat ${LOCKFILE}`; then
    echo "An instance of this script is already running."
    exit
fi

# make sure the lockfile is removed when we exit. Then: claim the lock
trap "command rm -f -- $LOCKFILE; exit" INT TERM EXIT
echo $$ > $LOCKFILE

# also create a tempfile, and make sure that's removed too upon exit
tmp=$(tempfile) || exit
trap "command rm -f -- '$tmp'" INT TERM EXIT



# ----------------------------------------
# option 1
# ----------------------------------------
# find your specific files
find "$1" -type f [INSERT SPECIFIC SEARCH PATTERN HERE] > "$tmp"
cat $tmp | rm 

# ----------------------------------------
# option 2
# ----------------------------------------
command rm -r "$1"



# remove the lockfile, tempfile
command rm -f -- "$tmp" $LOCKFILE
Run Code Online (Sandbox Code Playgroud)

此脚本首先将其自己的进程优先级和diskIO优先级设置为非常低的值,以确保其他正在运行的进程尽可能不受影响.

然后它确保它是唯一运行的进程.

脚本的核心非常符合您的偏好.您可以使用rm -r,如果你是确保整个目录可以indesciminately删除(选项2),也可以使用find更具体的文件删除(选项1,可能是使用命令行选项"$ 2"和ONW.为了方便).

在上面的实现中,选项1(find)首先将所有内容输出到临时文件,因此该rm函数只被调用一次而不是在每个文件找到之后find.当文件数量确实很大时,这可以节省大量时间.在缺点方面,临时文件的大小可能会成为一个问题,但这只有在您删除数十亿个文件时才会发生这种情况,而且,因为diskIO具有如此低的优先级,使用临时文件后跟一个文件rm可能总共是比使用find (...) -exec rm {} \;选项慢.与往常一样,您应该尝试一下,看看哪种最适合您的需求.

编辑:根据user946850的建议,您也可以跳过整个临时文件并使用find (...) -print0 | xargs -0 rm.这具有更大的内存占用,因为所有匹配文件的所有完整路径都将插入RAM中,直到find命令完全结束.从好的方面来说:由于写入tempfile而没有额外的文件IO.选择哪一个取决于您的用例.