# Make rm move to trash

Is there a Linux script / application which, instead of deleting files, moves them to a special “trash” location? I’d like this as a replacement for rm (maybe even aliasing the latter; there are pros and cons for that).

By “trash” I mean a special folder. A single mv $* ~/.trash is a first step, but ideally this should also handle trashing several files of the same name without overwriting older trashed files, and allow to restore files to their original location with a simple command (a kind of “undo”). Furthermore, it’d be nice if the trash was automatically emptied on reboot (or a similar mechanism to prevent endless growth). Partial solutions for this exist, but the “restore” action in particular isn’t trivial. Are there any existing solutions for this which don’t rely on a trash system from a graphical shell? (As an aside, there have been endless discussions whether this approach is justified, rather than using frequent backups and VCS. While those discussions have a point, I believe there’s still a niche for my request.) • This may be related to the SuperUser question Two commands to move files to trash. What's the difference?. I've used gvfs-trash in the past, but never had a need to restore from the command-line until you sparked my curiosity. The answer to the linked question may be of help. – ephsmith Jul 10 '12 at 23:02 • @ephsmith Thanks, good link. The problem with those approaches though is that they are bound to specific desktop shell (what’s the correct term here?) implementations, something which I want to avoid. – Konrad Rudolph Jul 11 '12 at 9:32 • Is moving files from any filesystem to your ~ intentional? Because some day you might be deleting a 4GB iso image residing on a dir mounted with sshfs from a really remote server. – Mischa Arefiev Jul 11 '12 at 11:40 • @Mischa To be honest, I didn’t put that much thought into it. That said, it should work with the usual user’s rights, so the target needs to be a location that is writeable and shouldn’t require too much configuration. – Konrad Rudolph Jul 11 '12 at 11:43 • Do whatever you want such as the solutions outlined in the answers below, but don't name it rm. As pointed out by others, renaming/repurposing standard commands leaves you vulnerable when you habitually try to use them on other systems, but it also will cause problems for anyone else (perhaps assisting you) using your system/account when unexpected results occur. – Joe Jul 14 '12 at 20:43 ## 9 Answers There is a specification (draft) for Trash on freedesktop.org. It is apparently what is usually implemented by desktop environments. A commandline implementation would be trash-cli. Without having had a closer look, it seems to provide the funtionality you want. If not, tell us in how far this is only a partial solution. As far as using any program as replacement/alias for rm is concerned, there are good reasons not to do that. Most important for me are: • The program would need to understand/handle all of rm's options and act accordingly • It has the risk of getting used to the semantics of your "new rm" and performing commands with fatal consequences when working on other people's systems • There is also libtrash which moves all deleted files automatically to the trash via LD_PRELOAD (but it seems to have several bugs). Autotrash helps to clean the trash in an easy way. – jofel Jul 11 '12 at 8:47 • I’m wondering about the getting-in-the-habit-of-using-rm thingy. I’m already in the habit, unfortunately. – Konrad Rudolph Jul 11 '12 at 9:43 • @jofel: libtrash has a really nice concept. A few layers deeper than the other approaches. It's a pity it is buggy (and does not seem very active). – zpea Jul 11 '12 at 10:29 • @KonradRudolph: I meant that one gets used to the fact that rm (the replaced one) does not really delete anything, so that one is less careful, as a restore is always possible. Of course, using rm itself is not a bad thing, nor is getting used to it. – zpea Jul 11 '12 at 10:33 • I’ve ended up using this solution, and disabling rm so I can’t use it accidentally (there’s still /bin/rm in case I really need it). – Konrad Rudolph Sep 5 '12 at 8:16 The previous answers mention commands trash-cli and rmtrash. Neither of those are found by default on Ubuntu 18.04, but the command gio is. Commanding gio help trash outputs: Usage: gio trash [OPTION…] [LOCATION...] Move files or directories to the trash. Options: -f, --force Ignore nonexistent files, never prompt --empty Empty the trash  I tested using gio trash FILENAME on the command line, and it works just like I'd selected the file in the file browser and clicked the DEL button: the file is moved to the desktop's Trash folder. (The command doesn't prompt for confirmation even though I did not use the -f option.) Deleting files this way is reversible, while being more convenient than redefining rm to be rm -i for safety and having to confirm each deletion, which still leaves you out of luck if you accidentally confirm a deletion you shouldn't have. I added alias tt='gio trash' to my alias definitions file; tt is a mnemonic for To Trash. Added on edit on 2018-06-27: On server machines, there is no equivalent of a trash directory. I've written the following Bash script that does the job; on desktop machines, it uses gio trash, and on other machines, moves the file(s) given as parameter(s) to a trash directory it creates. The script is tested to work; I use it all the time myself. Script updated on 2021-04-27. #!/bin/bash # # move_to_trash # # Teemu Leisti 2021-04-16 # # This script moves the files given as arguments to the trash directory, if they # are not already there. It works both on (Gnome) desktop and server hosts. (The # gio command only exists for Gnome.) # # The script is intended as a command-line equivalent of deleting a file from a # graphical file manager, which, in the usual case, moves the deleted file(s) to # a built-in trash directory. On server hosts, the analogy is not perfect, as # the script does not offer the functionality of restoring a trashed file to its # original location, nor that of emptying the trash directory; rather, it offers # an alternative to the 'rm' command, giving the user the peace of mind that # they can still undo an unintended deletion before emptying the trash # directory. # # To determine whether it's running on a desktop host, the script tests for the # existence of the gio command and of directory ~/.local/share/Trash. In case # both exist, the script relies on the 'gio trash' command. Otherwise, it treats # the host as a server. # # There is no built-in trash directory on server hosts, so the script creates # directory ~/.Trash/, unless it already exists. # # The script appends a millisecond-resolution time stamp to all the files it # moves to the trash directory, both to inform the user of the time of the # deletion, and to avoid overwrites when moving a file to trash. # # The script will not choke on a nonexistent file. It outputs the final # disposition of each argument: does not exist, was already in trash, or was # moved to trash. gio_command_exists=0 if command -v gio > /dev/null 2>&1 ; then gio_command_exists=1 fi # Exit on using an uninitialized variable, and on a command returning an error. # (The latter setting necessitates appending " || true" to those arithmetic # calculations and other commands that can return 0, lest the shell interpret # the result as signalling an error.) set -eu is_desktop=0 if [[ -d ~/.local/share/Trash ]] && (( gio_command_exists == 1 )) ; then is_desktop=1 trash_dir_abspath=$(realpath ~/.local/share/Trash)
else
trash_dir_abspath=$(realpath ~/.Trash) if [[ -e "$trash_dir_abspath" ]] ; then
if [[ ! -d "$trash_dir_abspath" ]] ; then echo "The file$trash_dir_abspath exists, but is not a directory. Exiting."
exit 1
fi
else
mkdir "$trash_dir_abspath" echo "Created directory$trash_dir_abspath"
fi
fi

for file in "$@" ; do file_abspath=$(realpath -- "$file") file_basename=$(basename -- "$file_abspath") if [[ ! -e$file_abspath ]] ; then
echo "does not exist:   $file_abspath" elif [[ "$file_abspath" == "$trash_dir_abspath"* ]] ; then echo "already in trash:$file_abspath"
else
if (( is_desktop == 1 )) ; then
gio trash "$file_abspath" || true else # The name of the moved file shall be the original name plus a # millisecond-resolution timestamp. beginning="$trash_dir_abspath/$file_basename"_DELETED_ON_ move_to_abspath="$beginning$(date '+%Y-%m-%d_AT_%H-%M-%S.%3N')" while [[ -e "$move_to_abspath" ]] ; do
# Generate a new name with a new timestamp, as the previously
# generated one denoted an existing file.
move_to_abspath="$beginning$(date '+%Y-%m-%d_AT_%H-%M-%S.%3N')"
done
# We're now almost certain that the file denoted by name
# $move_to_abspath does not exist. For that to be the case, an # extremely unlikely race condition would have had to take place: # some other process would have had to create a file with the name #$move_to_abspath after the execution of the existence test above.
# However, to make absolute sure that moving the file to the trash
# directory will always be successful, we shall give the '-f'
# (force) flag to the 'mv' command.
/bin/mv -f "$file_abspath" "$move_to_abspath"
fi
echo "moved to trash:   $file_abspath" fi done  Trash-cli is a linux application that can be installed using apt-get in Ubuntu or yum in Fedora. Using the command trash listOfFiles will move the specified into your trash bin. Here's a quick and dirty trash system that copes with name clashes and even allows multiple deleted files on the same path as long as you don't delete more than one file per second. Warning: I typed this code directly into my browser. It's probably broken. Don't use it on production data. trash_root=~/.trash mkdir "$trash_root"
newline='
'
trash () (
time=$(date +%Y%m%d%H%M%S) for path; do case$path in /*) :;; *) path=$PWD/$path;; esac
mkdir "$trash_root${path%/*}"
case ${path##*/} in ?*.*) ext="${path##*.}"; ext="${ext##*$newline}";;
*) ext="";;
esac
metadata="Data: $hash.$ext
Date: $time Path:$path
"
hash=$(printf %s "$metadata" | sha1sum)
printf %s "$metadata" "$trash_root/$hash-$time-metadata"
mv "$path" "$trash_root/$hash.$ext"
done
)

untrash () (
IFS='
'
root=$PWD cd "$trash_root" || return 2
err=0
for path; do
if [ -e "$path" ]; then echo 1>&2 "Not even attempting to untrash$path over an existing file"
if [ $err -gt 2 ]; then err=2; fi continue fi case$path in /*) :;; *) path=$root/$path;; esac
if metadata=$(grep -l -F -x "Path:$path" *-metadata |
sort -t - -k 2 | tail -n 1); then
mv "${metadata%%-*}".* "$path"
else
echo 1>&2 "$path: no such deleted file" if [$err -gt 1 ]; then err=1; fi
fi
done
return $err )  Known issues: • Doesn't cope gracefully if you try to delete the same file several times concurrently. • The trash directory may become huge, the files should be dispatched into subdirectories based on the first few digits of the hash. • trash should cope with newlines in file names, but untrash doesn't because it relies on grep and the newlines are not escaped in the metadata file. There's a little utility called rmtrash which does this. It doesn't seem to respond to params like -r or -f (it appears to essentially just be moving the file/directory to the ~/.Trash directory), but it won't override files with the same name (it appends "Copy" to like-named files/directories). To install with brew brew install rmtrash alias rm='rmtrash' >> ~/.bashrc  Start by defining a move_to_trash function: move_to_trash () { mv "$@" ~/.trash
}


Then alias rm to that:

alias rm='move_to_trash'


You can always call old rm by escaping it with a backslash, like this: \rm.

I don't know how to make the trash directory empty on reboot (depending on your system, you may have to look into the rc* scripts), but it could also be worthwhile to create a cron task that empties the directory periodically.

• Unfortunately, that was the easy part … :/ – Konrad Rudolph Jul 10 '12 at 22:11
• This script could also create a text file in a hidden directory for each file which contains the directory it was in. A restore script could read the old location and move it back. – ephsmith Jul 10 '12 at 22:20
• This also has a hazard of multiple deleted files with the same name would collide in the trash directory, and only the last one "deleted" would survive to be able to be recovered. – killermist Jul 10 '12 at 23:05
• @killermist, yes. Of course one would need to do something additional with the move command. Name the "trashed" file whatever you want and keep the original path :| This all screams "why re-create the wheel". There are existing solutions to this problem. – ephsmith Jul 11 '12 at 0:47
• Also, use a different alias name. Work on another machine without your aliases, one call to rm and there go your files. del might be a better choice. – glenn jackman Jul 11 '12 at 0:51

You can use my del:

http://fex.belwue.de/fstools/del.html

del moves files in a .del/ subdirectory (and back)

usage: del [-v] [-u] file(s)
del [-v] -p [-r] [-d days] [directory]
del [-v] -l
options: -v   verbose mode
-u   undelete file(s)
-p   purge deleted files [older than -d days]
-r   recursive (all subdirectories)
-l   list deleted files
examples: del *.tmp         # delete all *.tmp files
del -u project.pl # undelete project.pl
del -vprd 2       # verbose purge deleted files older than 2 days


I am testing this very simple alternative, which creates a date versioned ~/.trash for me.

I belive it doesn't have the (really valid) problems mentioned by the accepted answer:

The program would need to understand/handle all of rm's options and act accordingly

You simply use rm something. Doesn't need to pass any flags. If you do, say, run rm -rf, it will ignore the r, as mv doesn't support it and the f won't really make a difference, as the the ~/.trash is date versioned.

It has the risk of getting used to the semantics of your "new rm" and performing commands with fatal consequences when working on other people's systems

Like I said, the new semantics would end up being me running rm something. If I go back to using this in other machines, it will only work for files. For folders it will give the usual "you are missing -r" type of error.

move_to_trash() {
local trash_dir
trash_dir="${HOME}/.trash" if [ ! -d "${trash_dir}" ]; then
echo "Trash directory doesn't exist. Creating..."
mkdir "${trash_dir}" echo "Created!" fi local new_dir_name new_dir_name="${trash_dir}/$(date +%Y-%m-%d_%H-%M-%S)/" mkdir "${new_dir_name}"

echo "Moving to: ${new_dir_name}" mv "$@" ${new_dir_name} echo 'Done!' } alias really-rm="/bin/rm" alias rm="move_to_trash"  • does it work for rm -rf ? – Akhil Jun 18 '20 at 13:10 • Since it doesn't really remove stuff, just move to another place, the -rf doesn't matter. I explained in more details throughout the answer. – marcelocra Jun 19 '20 at 1:18 In KDE 4.14.8 I used the following command to move files to trash (as if it were removed in Dolphin): kioclient move path_to_file_or_directory_to_be_removed trash:/  Appendix I: I found about the command with  ktrash --help ... Note: to move files to the trash, do not use ktrash, but "kioclient move 'url' trash:/"  Appendix II: the function (then source it in your .bashrc) function Rm { if [[ "$1" == '--help' ]] ; then
echo 'USAGE:'
echo 'Rm --help # - show help'
echo 'Rm file1 file2 file3 ...'
echo 'Works for files and directories'
return
fi
for i in "$@" ; do kioclient move$i trash:/ && echo "\$i was trashed"
done
}