1. 程式人生 > >Linux安全刪除大檔案的方法

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/