基于sqlite3的linux终端回收站,将回收站的数据在sqlite3中记录
支持多个同名文件的删除和恢复
_alias_rm__trash_by_sqlite3.sh
sh
shopt -s expand_aliases
trash_dir=~/.trash
mkdir -p $trash_dir
alias rm=trash
DB=$trash_dir/.trash.db
[ ! -e $DB ] && cat <<EOF | sqlite3 $DB
CREATE TABLE "FileInfoTab" (
"ID" INTEGER UNIQUE,
"SHA" TEXT UNIQUE,
"delTime" TEXT,
"FileName" TEXT,
PRIMARY KEY("ID" AUTOINCREMENT)
)
EOF
trash()
{
# 循环是因为可能rm多个文件
for arg in "$@"
do
# 判断文件存在,同时过滤掉rm命令的参数
if ls $arg > /dev/null
then
# 获取文件的绝对路径,传递进来的可能是一个文件 文件夹 符号链接
# 转换文件的名字
delTime=$(date +"%Y%m%d_%H%M%S")
FileName=$(python -c "import os; print(os.path.abspath('${arg}'))")
SHA=$(echo ${delTime}"@@@@"${delTime} | sha1sum | awk '{printf $1}' )
#echo ${trashname}
# 已存在的同名文件按数字重命名,避免覆盖
#echo "${SHA}","${delTime}","${FileName}"
printf "INSERT INTO \"FileInfoTab\" (\"SHA\",\"delTime\",\"FileName\") VALUES (\"${SHA}\",\"${delTime}\",\"${FileName}\");" | sqlite3 $DB
mv --backup=numbered $arg ~/.trash/${SHA}
fi
done
}
rl()
{
printf "SELECT \"ID\",\"delTime\", \"FileName\" FROM \"FileInfoTab\" ;" | sqlite3 $DB
}
ur()
{
for arg in "$@"
do
printf "SELECT FileName,SHA FROM FileInfoTab WHERE ID=$arg;" | sqlite3 $DB | awk -F'|' '{system("mv ~/.trash/"$2" "$1)}';
[ $? -eq 0 ] && printf "DELETE FROM FileName WHERE ID=$arg;" | sqlite3 $DB
done
}
rc()
{
read -p "DELETE ALL in trash, confirm?[n]" confirm
if [ $confirm ]
then
if [ $confirm = 'y' -o $confirm = 'Y' ]
then
/bin/rm -rf ~/.trash/*
printf "DELETE FROM FileName;" | sqlite3 $DB
fi
fi
}
回收站目录
>>> ls ~/.trash/ -a
. .. .trash.db e8803e54711118162819b392bdde4db8f75c092a
查看回收站
>>> rl
1|20241030_113345|/home/zhangbin/xxxx/xxxx/xxx/xxxx
恢复文件
sh
ur 1