Safer alternative to "rm"

Hi Everyone

For frequent rm users, we know that this can be a tricky command to use on scratch, as it fully deletes files and gives no space for mistake. We were talking about that on CFP’s slack channel, and I shared a workaround I use - maybe that could be useful for y’all too…

Simply put, you can create an alias that mimics rm, but actually moves the data to a trash folder on scratch, and then set up an automatically daily cleaning of that trash folder. This gives a few hours to fix rm mistakes.

The alias I use is:
alias rmt="mv -t /target/directory/with/created/trash/folder/ "

Then for the folder cleaning, I program to clean any file that has not been changed in more than 5 days:
find /target/directory/with/created/trash/folder -mindepth 1 -ctime +5 -delete

That works cause mv alters the change timestamp of the file. Since bash_profile is read at ssh login, it should work as long as you are regularly SSH’ing gadi.

If you want the alias to be a substitute to rm, to make rm safe, you can instead:
alias rm="mv -t /target/directory/with/created/trash/folder/ "

Hopefully that is useful for others :slight_smile: And feel free to suggest improvements!

2 Likes

A few caveats to keep in mind is that, this alias would work automatically in your SSH session, but it will only work in scripts if you use

shopt -s expand_aliases

And source your bash profile first.

Also, the rmt is automatically recursive, which is good to keep in mind

Some related tips to avoid data loss:

  • I remove my write permissions (chmod u-w) from files/directories I know I don’t want to delete
  • you can use rsync --hard-links --link-dest ... to make multi-snapshot backups (like Time Machine on macs), which uses hard links between snapshots to save space (and time copying)
  • rsync --remove-source-files ... is safer than mv as it can be interrupted and resumed from where it left off, and it only deletes from source if things have arrived at destination
2 Likes