Linux安全删除大文件的方法

Linux环境下,如果删除一个很大的单文件, 直接使用rm 等命令删除,会引起IO陡增, CPU陡增的情况,为平缓删除大文件带来的影响,使用truncate辅助,通过逐步的缩小文件,达到平滑删除的目的。

1. truncate 介绍

Usage: truncate OPTION... FILE...
Shrink or extend the size of each FILE to the specified size

A FILE argument that does not exist is created.

If a FILE is larger than the specified size, the extra data is lost.
If a FILE is shorter, it is extended and the extended part (hole)
reads as zero bytes.

Mandatory arguments to long options are mandatory for short options too.
  -c, --no-create        do not create any files
  -o, --io-blocks        Treat SIZE as number of IO blocks instead of bytes
  -r, --reference=FILE   use this FILE's size
  -s, --size=SIZE        use this SIZE
      --help     display this help and exit
      --version  output version information and exit

SIZE may be (or may be an integer optionally followed by) one of following:
KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.

SIZE may also be prefixed by one of the following modifying characters:
`+' extend by, `-' reduce by, `<' at most, `>' at least,
`/' round down to multiple of, `%' round up to multiple of.

Note that the -r and -s options are mutually exclusive.

 

2. 安全删除工具

#file name, default in current dir
LAGRE_FILE=$1

if [[ ! -f ${LAGRE_FILE} ]];then

        echo "${LAGRE_FILE} NOT FOUND, PLEASE CHECK FILE."
        exit 1

fi

#get file size
FILE_SIZE=`du -shm ${LAGRE_FILE} | awk -F ' ' '{print $1}'`

#default 20M 
DELETE_SPEED=20

#safe rm size 20M default
SAFE_SIZE=50

echo "CURRENT ${LAGRE_FILE} IS ${FILE_SIZE}M, NOW START DELETE..."

for ((i=${FILE_SIZE}; i>${SAFE_SIZE}; i=i-${DELETE_SPEED}))
do

        echo "truncate ${i}M ......";
        truncate -s ${i}M ${LAGRE_FILE} ;

        sleep 2;
done

LAST_FILE_SIZE=`du -shm ${LAGRE_FILE} | awk -F ' ' '{print $1}'`

echo "CURRENT ${LAGRE_FILE} IS ONLY ${LAST_FILE_SIZE}M, DELETE IT..."

rm -rf ${LAGRE_FILE}

if [[ ! -f ${LAGRE_FILE} ]];then

        echo "${LAGRE_FILE} DELTE SUCC."

else

        echo "${LAGRE_FILE} DELTE FAILED, PLEASE CHECK AND DELTE IT MANUAL"
        exit 2

fi

 

3. 工具改善

此工具可以继续封装以支持递归删除目录下很多大文件的功能 

参考 http://darcy.org.cn/2015/06/19/linuxxia-ru-he-an-quan-shan-chu-wen-jian/

 

posted @ 2018-12-05 20:16  skadieye  阅读(2137)  评论(0编辑  收藏  举报