Daily Ubuntu / Linux news and application reviews.


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:

# command name: trash-rm
shopt -s extglob
declare -a cmd
((i = 0))
for f in "$@"
case "$f" in
if [ -n "$tmp" ]
#echo "\$tmp == $tmp"
recursive=0 ;;
(--recursive) recursive=0 ;;
if [ $recursive != 0   -a  -d "$f" ]
echo "skipping directory: $f"
fi ;;
trash "${cmd[@]}"

Update: starting with Ubuntu 12.04 Precise Pangolin, trash-cli provides the command "trash-put" to trash files, instead of the previous "trash" command, so in the code above, on the last line, replace "trash" with "trash-put" for Ubuntu 12.04+.

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:

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):

In the latest trash-cli (Ubuntu 12.04; trash-cli version 0.11.3+git20120324), the commands have changed:

trash-empty empty the trashcan(s).
trash-list list trashed file.
restore-trash restore a trashed file.

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"!

Newer Post
Older Post