原理为自己定义rm的操作:将要删除的目标文件或目录移动到自定义的回收站里面。
首先创建脚本 saferm.sh:
#!/bin/bash
#define the trash can path
TRASH_DIR="$HOME/.trash"
mkdir -p $TRASH_DIR
#rm count
count=0
#ranging all the targets
for i in $*; do
#if the current target does not exist, just ignore it
if [ ! -f $i ] && [ ! -d $i ];then
echo '---not found:'$i
else
#create a time stamp to indicate when the target is removed
STAMP=`date +%s`
fileName=`basename $i`
#move the target to the trash dir to finish the fake rm action
mv $i $TRASH_DIR/$fileName.$STAMP.$count
#delete count
count=`expr $count + 1`
fi
done
echo "trash dir: $TRASH_DIR"
exit 0
这个脚本实现了基本功能:把每个移除目标移动到垃圾箱中,并根据时间戳重命名。
然后别忘了加可执行权限:
chmod +x saferm.sh
我们把脚本放到合理的地方,方便调用:
mv saferm.sh /home/wzj/software/
也可以给脚本创建别名:
alias saferm="sh /home/wzj/software/saferm.sh"
使用方法:
saferm ./a.txt temp_dir c.xlsx
如果需要永久修改,则再把上面的操作加到启动脚本中即可,比如~/.bashrc、~/.zshrc等,但是只有当前用户登录后有效。
注意,一个小建议:不要对rm 使用该alias,平时使用rm时使用/bin/rm提醒自己在干什么。如果按照上文方式设置alias别名,在用sudo rm时可能会调用/bin/rm, 而不是我们的saferm,特别在shell脚本中要尤其注意。所以为了安全起见,请使用alias saferm,必要时使用/bin/rm。