public
Last active

I have committed a lot of terrible mistakes involving rm, so I coded this script to prevent any further accidents.

  • Download Gist
trash.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
#!/usr/bin/env node
 
var fs = require('fs');
 
var help = "Usage : trash [-lhx] files...\n\t-l : list trashcan\n\t-x : cancel (files: timestamp)\n\t-h : help";
var trash = process.env['HOME'] + "/.trash/";
 
(function(argv, log, error) {
argv = require('optimist').parse(argv);
if (typeof argv.l === 'string') {
argv._.unshift(argv.l);
argv.l = true;
}
if (typeof argv.x === 'string') {
argv._.unshift(argv.x);
argv.x = true;
}
 
if (!argv.l && (argv._.length == 0 || argv.h)) {
log(help);
return;
}
 
var timestamp, rmfolder;
 
if (argv.l) {
log(fs.readdirSync(trash).join(' '));
return;
}
 
if (argv.x) {
timestamp = argv._[0];
rmfolder = trash + timestamp + '/';
if (!fs.existsSync(rmfolder)) {
error("Error: %s does not exist!", rmfolder);
return;
}
fs.readdirSync(rmfolder).map(function(item) {
log("Recovering: %s", item);
fs.renameSync(rmfolder + item, item);
});
fs.rmdirSync(rmfolder);
return;
}
 
 
timestamp = Date.now().toString(36).toLowerCase();
rmfolder = trash + timestamp + '/';
log("Trash can ID: %s", timestamp);
fs.mkdirSync(rmfolder);
 
for (var i = 0; i < argv._.length; i++) {
fs.renameSync(argv._[i], rmfolder + argv._[i]);
}
}(process.argv.slice(2), console.log.bind(console), console.error.bind(console)));

PS. mkdir ~/.trash before use this.

PPS. I know that there are some trashcan utilities.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.