Linux安全删除大文件的方法

本文介绍了一种在Linux环境下平滑删除大文件的方法,避免了直接删除引起的IO和CPU资源骤增。通过使用truncate命令逐步缩小文件大小,实现对大文件的安全删除。文章还提供了一个脚本示例,用于自动化这一过程。

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/

 

转载于:https://www.cnblogs.com/skadieye/p/10073131.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值