安全 rm

让 rm -rf * 不再那么可怕

新建可执行脚本,替换rm 命令

1. 创建脚本
cd /
mkdir rmbin
cd rmbin
vi myrm
复制下面脚本内容至myrm

2. 设置环境变量
vi ~/.bash_profile
---
PATH="/rmbin:${PATH}"
export PATH
---
[[ -s .bashrc ]] source ~/.bashrc # 如果有.bashrc就运行该脚本

3. 
cd ~
vi ~.bashrc
增加以下代码:
----
alias rm=myrm
myclear(){
    ls ~/trash
    if [ $? -eq 0 ]; then
        read -p "Do you want to clear all files in ~/trash (yes/no): " var
        if [ $var = "yes" ]; then
            \rm -rf ~/trash/*
        elif [ $var = "no" ]; then
            echo "nothing to do"
        fi
    fi
}
----

4. 重启终端。

5.使用
rm xxx # 删除文件
rm -rf xxx # 删除文件目录
myclear # 查看已删除的文件或文件夹,并提示是否删除

脚本内容

TRASH=~/trash

set -e  #Exit immediately if any untested command fails in non-interactive mode. 

if [[  $1 =~ ^-[^rf] ]]; then
    echo "usage: rm [-rf] files"
    exit 1
fi

if [ $# == 0 ]; then
    echo "usage: rm [-rf] files"
    exit 2
fi 

mkdir -p $TRASH
echo rm $@

if [[ $1 =~ ^-[rf]|^-rf$ ]]; then
    for (( i=2;i<=$#;i++ )); do
        eval file="\${$i}"         
        echo "$file => ~/trash"
        mv "$file" $TRASH
    done
else 
    for (( i=1;i<=$#;i++ )); do
        eval file="\${$i}"
        echo "$file => ~/trash"
        mv "$file" $TRASH
    done    
fi

你可能感兴趣的:(安全 rm)