给自己Linux搞个『回收站』,防止文件误删除

担心在linux中疯狂输出的时候误删文件?也许你需要回收站了

linux没有像windows里一样的回收站,工作时候删除文件容易不小心删错,造成麻烦的后果。所以给自己整了个回收站。

文件删除,新建~/opts/move_to_trash.sh,然后在里面新增,将${your_name}改成你的用户名。同时在~/.bashrc中alias rm命令到这个脚本,即是alias rm='sh ~/opts/move_to_trash.sh',别忘了source ~/.bashrc使其生效。 在删除的时候,会在原文件名字后面新增删除时的时间戳信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
PARA_CNT=$#
USER_HOME=/home/${your_name}
TRASH_DIR="${USER_HOME}/.trash" # 指定垃圾箱目录
mkdir -p ${TRASH_DIR}
for i in $*; do
if [ -f "$i" ] && [ `ls -l $i|awk '{print $5}'` -gt 1073741824 ]; then
echo "$i size is larger than 1K, can not delete it !"
continue
fi
STAMP=`date +%Y%m%d` # 删除时间
fileName=`basename $i`
mv $i $TRASH_DIR/$fileName.$STAMP # 删除文件命令,放到垃圾箱
done
echo "remove ${PARA_CNT} file/folder, fetch back if you need at ${TRASH_DIR}"

同时,可以考虑新增一个清除回收站的脚本,定期运行保证空间干净。由于保存了时间戳,时间超过当前7天的文件就可以删除掉了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/bin/bash

KEEP_DAY_DURATION=7

TRASH_PATH="/data1/${your_name}/.trash"
current_date=$(date +%Y%m%d)
date_minus_10=$(date -d "$current_date -${KEEP_DAY_DURATION} days" +%Y%m%d)
ddl_timestamp=$(date -d "$date_minus_10" +%s)
echo "current date is ${current_date}, the files in trash before ${date_minus_10} will be COMPLETELY delete, are your sure?"
read -p "Do you want to continue? (y/n) " answer

case ${answer} in
[Yy]* )
echo "deleting..."
ls -l ${TRASH_PATH} | awk -F " " 'NF==9{print $NF}' > .tmp
read -ra READ_LIST -d '' < .tmp
rm .tmp
for filename in "${READ_LIST[@]}";
do
filedate=`echo ${filename} | awk -F "." '{print $NF}'`
filedate_stamp=`date -d "$filedate" +%s`
if [ $filedate_stamp -lt $ddl_timestamp ]; then
abs_filename="${TRASH_PATH}/${filename}"
/usr/bin/rm -rf ${abs_filename}
echo "delete ${abs_filename}"
fi
done
;;

[Nn]* )
echo "skip and exit"
exit -1
;;

* )
echo "not valid answer ${answer} and exit"
exit -1
;;
esac