32MB.CN

Make "rm" Move Files To Trash Instead Of Completely Removing Them
To get the "rm" (but you can alias some other command lik...
扫描右侧二维码阅读全文
07
2015/10

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 or Debian, simply run this command:

sudo apt-get install trash-cli

2. Set up the script

In Ubuntu or Debian enter this in a terminal:

#!/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[@]}"

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:

vim ~/.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".

Last modification:October 7th, 2015 at 03:06 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment