[Linux]防止误删操作

原理为自己定义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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值