12 Jan 2009

Trash rather than rm

One of the most powerful/dangerous commands in linux is the “rm” command.  It removes the file from the filesystem and whilst with some media formats it is possible to recover an rm’d file in ext3 it is almost impossible to get that file back (without a hexdumper and lots of time on your hands to manually re-link the file).

After doing a bit of work the other day but before my nightly backup had run I went into the directory I had been coding in and decided to get rid of the backup files that had been created.  The backup files were like the normal files except they had a tilda attached, ie, filename.txt~, so to delete all the backup files in one go I quickly typed in:

1
rm *~

Except that’s not what I typed.  I missed the tilde off the end and wiped all the files from that directory.  Oops.  Nightly backup not yet run.  Major Oops.  After chuckling that I do make backups a priority and I tell people to make backups a priority I hadn’t done it myself.  Too late.

I did get the files back because, thankfully,  my data store is an SDHC card formatted to vfat (windows) so only the FAT entry had been deleted - more on that in my next post.

But that left me wondering.  I rarely need all the power of rm - whenever I’m using it from the commandline I could think of virtually no circumstances where I would prefer to unlink the file altogether rather than just move it to the trash.  As I looked around the net I noticed lots of suggestions from people to replace rm altogether or to create an alias for rm that does something else, but the problem with that is that lots of programs rely on rm being the way it is and taking specific arguments, etc.  To change it just for me would probably break the system or applications that I have installed or could install at any time.

The solution I settled on was to stop using rm from the commandline altogether and learn to use an alias I created called “trash” whenever I wanted to delete a file from the commandline.  All you need to do to use it is to open your ~/.bashrc file and put the following line in it somewhere (at the end works just fine):

1
alias trash="mv -t ~/.local/share/Trash/files --backup=t --verbose"

Obviously if your trash is in a different location you need to change the location above - what I’ve written above is correct for Ubuntu.  Now when you “trash” a file it will go into your trash bin and is therefore retreivable rather than being deleted forever.

Such a simple script doesn’t work perfectly of course and if you delete a huge file on a removable local device you’ll notice that it will move the file to the trash bin on another device and that will take some time.  What I could do with now is to know the name of the trash folder on the device on which the file is located and send it there.

comments powered by Disqus