安全的rm -rf 让你在Linux删除的文件有地方找回
2017-04-03
服务器
一个不小心rm掉文件了吧?
后悔莫及了吧!
把这段代码加入你的home目录的.bashrc或者.zshrc就可以了
工作原理:
在你的home目录会创建一个.trash文件夹
里面会按照删除时间 年-月-日/小时/ 进行归档已删除的文件
然后会删除一个月以前的文件夹
就是这样!
## by 3haku.net
function rm() {
# garbage collect
now=$(date +%s)
for s in $(ls --indicator-style=none $HOME/.trash/) ;do
dir_name=${s//_/-}
dir_time=$(date +%s -d $dir_name)
# if big than one month then delete
if [[ 0 -eq dir_time || $(($now - $dir_time)) -gt 2592000 ]] ;then
echo "Trash " $dir_name " has Gone "
/bin/rm $s -rf
fi
done
# add new folder
prefix=$(date +%Y_%m_%d)
hour=$(date +%H)
mkdir -p $HOME/.trash/$prefix/$hour
if [[ -z $1 ]] ;then
echo 'Missing Args'
return
fi
echo "Trashing "$1
mv $1 $HOME/.trash/$prefix/$hour
}