Emulating the Recycling Bin in bash


I just ran into a problem where I accidentally erased a file that was very important and could not recover from it (it was a monstrous statistical model that takes about 5 hours to re-train…). I decided I had enough of this and needed a way to be able to recover from those silly mistakes (apparently not making them in the first place just wasn’t an option…) I wondered if anybody ever run into this problem, and what was their personal solution? Here is what I found and tested today (it works pretty well).

I know that there are processes that backs up your whole $HOME on a regular schedule, I forget the name of this process, but that’s not exactly what I need. I always liked the idea of a “recycling bin” from the GUI Operating Systems like Windows (or KDE) and decided that that’s exactly what I needed. I found the next best thing on the internet (See John’s Bash Tools for his original post).

I simply put this in my .bashrc and now can use “junk” instead of “rm”… It’s a pretty neat little trick actually. I then can use “empty_junk” every now and then to keep the size of my home reasonable. I could even add “empty_junk” in my .bashrc so that it gets emptied everytime I log on (I won’t because I often log onto twice at the same time and would create problems…).

##############################
# Emulating a reclycling bin #
##############################
# This function creates a directory called .junk
# and creates directories labeled by the date
# inside of this directory. Then, when a file is
# "junk"ed, it is actually just moved to this
# directory. The command line accepts as many
# files as you would care to junk, and can even
# work on entire directories. Be careful, since it
# is really just a wrapped "mv" command, you may
# overwrite your junked files if they both have
# the same name and end up in the root directory.

function junk () {
    TODAY=$(date +%d-%m-%y)
    if [ ! -e $HOME/.junk/$TODAY ]
    then
        mkdir -p $HOME/.junk/$TODAY
    fi

    for x in $@
    do
        mv $x $HOME/.junk/$TODAY
    done
}

# A very simple function to empty the trash.
# I set -Ri so that it recurses but prompts you.

function empty_junk () {
    rm -Ri $HOME/.junk/*
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s