Linux 回收站——防止误删文件
方法 1:bash 脚本(写入~/.bashrc 文件),简单实用无外部依赖
提供如下四个命令:
rmv a <b c>:move a <b and c> to recycle bin
unrmv a <b>: restore a from recycle bin to <b> (default b='./')
lsrmv: list recycle bin
clearrmv: clear recycle bin
# >>> zzh: recycle bin >>>
## define trash dir and make it
# trash_path="~/.trash"
# trash_path="$HOME/.trash"
trash_path="/hhd/2/zzh/.trash/" # # assign one according to your need
# make the $trash_path dir if there is no one.
if [ ! -d $trash_path ]; then
mkdir -p $trash_path
fi
## define alias
alias rmv=trash # rmv a <b c>:move a <b and c> to recycle bin
alias unrmv=restorefile # unrmv a <b>: restore a from recycle bin to <b> (default b='./')
alias lsrmv=lstrash # lsrmv: list recycle bin
alias clearrmv=cleartrash # clearrmv: clear recycle bin
## functions
# move to recycle bin
trash() {
if [[ $# -le 0 ]]; then
echo "please assign the parameters: delete_file"
return
fi
for i in $*; do
STAMP=$(date "+%Y-%m-%d")
file_srcpath=$(echo $i | sed 's/\(.*\)\/$/\1/g')
file_dstpath=$trash_path/$STAMP/$file_srcpath
if [[ -e $file_dstpath ]]; then
suffix=$(date "+%Y%m%d%H%M%S")
file_dstpath=${file_dstpath}_${suffix}
fi
file_path_dir=$(dirname $file_dstpath)
mkdir -p $file_path_dir
mv $file_srcpath $file_dstpath
done
}
# restore from recycle bin
restorefile() {
if [[ $# -eq 1 ]]; then
trash_file=$1
restore_dir="./" # default restore dir = ./
elif [[ $# -eq 2 ]]; then
trash_file=$1
restore_dir=$2
else
echo "please assign the parameters: trash_file <restore_dir>"
return
fi
restore_to_path=$restore_dir/${trash_file:11}
if [[ -d ${restore_to_path} ]]; then
echo "mv -b $trash_path/$trash_file/* $restore_to_path"
mv -b $trash_path/$trash_file/* $restore_to_path
else
trash_file_dir=$(dirname $trash_file)
restore_to_dir=$restore_dir/${trash_file_dir:11}/
mkdir -p $restore_to_dir
echo "mv -b $trash_path/$trash_file $restore_to_dir"
mv -b $trash_path/$trash_file $restore_to_dir
fi
find $trash_path -mindepth 1 -depth -type d -empty -delete # delete empty dirs
}
# show recycle bin contents
lstrash() {
dirs=$(find $trash_path -type d -links 2)
files=$(find $trash_path -maxdepth 2 -mindepth 2 -type f)
printf "\n------ Dirs ------\n"
while read -r line; do
echo "${line/$trash_path/}"
done <<<"$dirs"
printf "\n------ Files ------\n"
while read -r line; do
echo "${line/$trash_path/}"
done <<<"$files"
}
# clear recycle bin
cleartrash() {
read -p "Sure to clear the trash box?[y/n]" confirm
[[ $confirm == 'y' ]] || [[ $confirm == 'Y' ]] && /bin/rm -rdf $trash_path/*
}
# <<< zzh: recycle bin <<<
如果需要定期清理回收站,可以使用 Linux 的定时任务命令 crontab 定期删除 trash 目录,但是不建议这么做,因为 rm 命令有风险(惨痛教训!),还是自己需要的时候手动运行命令 clearrmv
清理回收站比较好。
方法 2:开源命令行工具,功能更全面
GitHub - andreafrancia/trash-cli: Command line interface to the freedesktop.org trashcan.