Sunday, December 16, 2012

A safe `rm' for bash


I have many times typed
rm -rf *  !!
in a hurry, unknowingly
This can be really really upsetting, depending on which directory you
are in ! :)
While talking to my teammates on how to make rm a little safe, I
tried the following:
alias rm to a function, which will check the args and then force
interactive mode. The option check is simple, the only problem is
your function will not receive '*', as the shell would have already
expanded it!
The solution is to club alias and function, with disable globbing
and then re-enable it!

Thanks to Simon's article which helped me with this.

Full bash function here:

alias rm='set -f;rm_in'
rm_in() {
    local YN HIT LAST N
    N=$#
    LAST=${!N}
    if [[ $1 =~ -[fr]+ ]] && [[ $2 == '*' ]] ; then
        HIT=1
        echo -n "Are you insane ? (y/n): "
        read YN
    fi
    if [[ -z $HIT ]] ; then
        if [[ $LAST == '*' ]]; then
            HIT=1
            echo -n "This is li'll scary, are you sure ? (y/n): "
            read YN
        fi
    fi
    set +f
    if [[ ! -z $YN ]]; then
        if [[ $YN =~ [yY] ]] ; then
            echo "May it be! .."
            eval command rm "$@"
        else
            echo "Thank God!"
        fi
    fi
    if [[ -z $HIT ]] ; then
        eval command rm "$@"
    fi
}
  

No comments: