linux没有像windows里一样的回收站,工作时候删除文件容易不小心删错,造成麻烦的后果。所以给自己整了个回收站:
文件删除,新建~/opts/move_to_trash.sh
,然后在里面新增,将${your_name}
改成你的用户名。同时在~/.bashrc
中alias rm命令到这个脚本,即是alias rm='sh ~/opts/move_to_trash.sh'
,别忘了source ~/.bashrc
使其生效。 在删除的时候,会在原文件名字后面新增删除时的时间戳信息。
#!/bin/bash
PARA_CNT=$#
USER_HOME=/home/${your_name}
TRASH_DIR="${USER_HOME}/.trash" # 指定垃圾箱目录
mkdir -p ${TRASH_DIR}
for i in $*; doif [ -f "$i" ] && [ `ls -l $i|awk '{print $5}'` -gt 1073741824 ]; thenecho "$i size is larger than 1K, can not delete it !"continuefiSTAMP=`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天的文件就可以删除掉了。
#!/bin/bashKEEP_DAY_DURATION=7TRASH_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) " answercase ${answer} in[Yy]* )echo "deleting..."ls -l ${TRASH_PATH} | awk -F " " 'NF==9{print $NF}' > .tmpread -ra READ_LIST -d '' < .tmprm .tmpfor filename in "${READ_LIST[@]}";do filedate=`echo ${filename} | awk -F "." '{print $NF}'`filedate_stamp=`date -d "$filedate" +%s`if [ $filedate_stamp -lt $ddl_timestamp ]; thenabs_filename="${TRASH_PATH}/${filename}"/usr/bin/rm -rf ${abs_filename}echo "delete ${abs_filename}"fidone;;[Nn]* )echo "skip and exit"exit -1;;* )echo "not valid answer ${answer} and exit"exit -1;;
esac