分类: Python/Ruby
2013-01-16 18:27:41
原文地址:Linux/Unix回收站(trash) 作者:liurenzhong1984
大家非常熟悉Windows系统的回收站,而Linux/Unix字符界面貌似没有类似的功能。个人觉得这功能是蛮实用的,是对系统误删的一种保护。有些资深的Unix爱好者觉得无需此功能,因为这样就可能不够“unix”了,但总比误删了一些比较重要即或不重要但是需要的文件时那种蛋疼的感觉要痛快些吧。如果你不小心删掉本不该删除的东东,然后喜出望外地从回收站里找回时的那种快感一定能让你开心一天。*^◎^*
那我们怎么实现Linux/Unix版的回收站功能呢?就是让Unix的删除命令不是彻底删除文件,而是将其移至回收站里,然后根据需要可以定期清理回收站里的内容;重要的是,你可以随时找回那些误删的文件。我们可以通过别名(alias)将rm命令设成我们的回收(trash)命令。
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 40 41 42 43 44 45 | #!/bin/sh # # FILE: trash.sh # DESC: 移动垃圾到回收站 # # ORIG: Renzo.Liu # DATE: 2011/11/27 # # TRASHDIR= "${HOME}/.trash/$(date +%Y%m%d)" TRASHLOG= "${TRASHDIR}/trash.log" if [ $ # -eq 0 ] then exit fi [ -d ${TRASHDIR} ] || mkdir -p ${TRASHDIR} [ -s ${TRASHLOG} ] && echo >> ${TRASHLOG} echo "===================================TRASHLOG ===================================" >>${TRASHLOG} echo -e " $(date " +DATE:%D TIME:%T ") USER:$(whoami) IP:$(who -m|awk '{print $5'}|tr -d '(|)')" >> ${TRASHLOG} echo "--------------------------------------------------------------------------------" >> ${TRASHLOG} for SRCFILE in $* do if [ ! -e "${SRCFILE}" ] then echo "\"${SRCFILE}\" doesn't exist!" continue fi # Move trashery to recycle bin TRASHERY=${TRASHDIR}/$( basename ${SRCFILE})_$$ mv "${SRCFILE}" "${TRASHERY}" # Write trashery log echo "\"${SRCFILE}\" has been moved to recycle bin!" echo "[$(pwd)/${SRCFILE}] => [${TRASHERY}]" >>${TRASHLOG} done # End of trash.sh |
alias rm="trash.sh"
另外,此脚本还会登记删除动作的要素包括日期、时间、用户以及IP地址。这样可以让管理员溯根追源。实际使用中,确实有些东西需要彻底删除,譬如一些大的垃圾文件或者清理回收站时。这时就需要("\rm"命令)强制删除,而不再使用rm别名(trash命令)删除。
1 2 | renzo@renzo:/home/renzo/tmp> ls *.txt 1 .txt 2 .txt 3 .txt 4 .txt |
1 2 3 4 5 | renzo@renzo:/home/renzo/tmp> rm *.txt "1.txt" has been moved to recycle bin! "2.txt" has been moved to recycle bin! "3.txt" has been moved to recycle bin! "4.txt" has been moved to recycle bin! |
1 2 | renzo@renzo:/home/renzo/.trash/ 20130103 > ls 1 .txt_36961 2 .txt_36961 3 .txt_36961 4 .txt_36961 trash.log |
1 2 3 4 5 6 7 8 | 1renzo@renzo:/home/renzo/.trash/ 20130103 > cat trash.log 1 =================================== TRASHLOG=================================== DATE: 01 / 03 / 13 TIME: 21 : 58 : 50 USER:renzo IP: 192.168 . 48.1 -------------------------------------------------------------------------------- [/home/renzo/tmp/ 1 .txt] => [/home/renzo/.trash/ 20130103 / 1 .txt_36961] [/home/renzo/tmp/ 2 .txt] => [/home/renzo/.trash/ 20130103 / 2 .txt_36961] [/home/renzo/tmp/ 3 .txt] => [/home/renzo/.trash/ 20130103 / 3 .txt_36961] [/home/renzo/tmp/ 4 .txt] => [/home/renzo/.trash/ 20130103 / 4 .txt_36961] |