rm is a basic command line tool on Linux OS. It is efficient but can be dangerous if we use incorrectly because it can delete all files and can’t undo. The post shows a way to change its default behavior.

Create Shell Script myrm

Write a shell script and make it exit if there is any error in process.

#!/usr/bin/bash
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

The above shell script is useful for some dangerous command statements such as rm *, rm -rf *, rm -f * and rm -r.
We add " around $file due to space symbol in the file name.

Put Script File In /usr/bin/

The environment variable $PATH contains /usr/bin/ in the most cases. You can add PATH="/usr/bin":$PATH to the file /etc/profile if it is not.
Make the script file executable, chmod +x myrm
Move it to /usr/bin/.

Modify ~/.bashrc

Add the following content in the file ~/.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
}

Input rm and you will see tips.

[yang@ver-text-1 Download]$ rm
usage: rm [-rf] files

If it doesn’t work, type source ~/.bashrc and press enter.

After that you can use rm safely and myclear will help you to clear the folder ~/trash.
Note: the new rm works in the terminal. For the script file, rm means the original system user commands tool.

Categories: ShellTool

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments

Tex To PDF
: convert the Latex file which suffix is tex to a PDF file

X
0
Would love your thoughts, please comment.x
()
x