Powered By

Powered by Blogger

Jumat, 19 Februari 2010

Make "rm" Move Files To Trash Instead Of Completely Removing Them

To get the "rm" (but you can alias some other command like "del" or keep the original "trash" command!) command to move the file(s) to trash instead of removing them completely, you must install the trash-cli utility and set an alias for "rm" to use trash-cli. But trash-cli also removes folders, even without using the "-r" (recursive) option, so in this post I will share a script created by grizzly which will only remove folders when the "-r" argument is used.


Here is the complete mini-guide to setting "rm" to move files (and folders) to trash:


1. Install trash-cli

This package provides a command line interface trashcan utility compliant with the FreeDesktop.org Trash Specification. It remembers the name, original path, deletion date, and permissions of each trashed file.


In Ubuntu, simply run this command:
sudo apt-get install trash-cli


2. Set up the script

In Ubuntu enter this in a terminal:
sudo gedit /usr/local/bin/trash-rm

And paste this in the newly opened file, then save it:

#!/bin/bash
# command name: trash-rm
shopt -s extglob
recursive=1
declare -a cmd
((i = 0))
for f in "$@"
do
case "$f" in
(-*([fiIv])r*([fiIv])|-*([fiIv])R*([fiIv]))
tmp="${f//[rR]/}"
if [ -n "$tmp" ]
then
#echo "\$tmp == $tmp"
cmd[$i]="$tmp"
((i++))
fi
recursive=0 ;;
(--recursive) recursive=0 ;;
(*)
if [ $recursive != 0 -a -d "$f" ]
then
echo "skipping directory: $f"
continue
else
cmd[$i]="$f"
((i++))
fi ;;
esac
done
trash "${cmd[@]}"


Then make it executable by opening a terminal and running this:
sudo chmod +x /usr/local/bin/trash-rm


3. Create an alias for "rm" to use "trash-rm"

In Ubuntu, run this in a terminal:
gedit ~/.bashrc

and enter this at the end of the file:
alias rm="trash-rm"

and save it.

Then reload bashrc by running the following command in a terminal:
bash

That's it! Now try it out by deleting files the way you always do, using "rm" and "rm -r".


Final trash-cli tips


Since you've installed the trash-cli utility, now you can use the following commands for manipulating the trash from the command line (the names are self explanatory):
empty-trash
list-trash
restore-trash


Update: to get this to work for "sudo rm" as well, copy wilo108's sudo wrapper in your ~/.bashrc file. Without it, this will not work when "rm" is used with "sudo"!

Tidak ada komentar:

Posting Komentar