Monday, October 5, 2009

Shell script for moving files to trash

(updated 06-10-2009, bottom paragraph)

Ubuntu keeps its trash in ~/.local/share/Trash/files, and stores metadata (ie. deleted from where, deleted when) in a sibling info/ folder. This script tries to move files to trash just as the file browser would do, so you can easily restore it later.

Save it as trash (or whatever you like) in your $HOME/bin folder (don't forget to chmod u+x it), and use it instead of rm.

#!/bin/bash
#
# A shell script for moving files and folders to your (Gnome) trash can,
# allowing to restore files from the file browser.

TRASH="$HOME/.local/share/Trash/"
TRASH_FILES="$TRASH/files/"
TRASH_INFO="$TRASH/info/"
pwd=`pwd`;
until [ "$#" = "0" ];do
fullpath=`find $pwd -maxdepth 1 -name "$1"`;
trashinfofile="$TRASH_INFO$1.trashinfo";
trashdate=`date +%FT%T`;
mv $1 "$TRASH_FILES" &&
echo "[Trash Info]
Path=$fullpath
DeletionDate=$trashdate" > "$trashinfofile" &&
echo "Moved $fullpath to $TRASH_FILES and updated trash metadata." ||
echo "Could not move $fullpath to $TRASH_FILES, or could not update trash metadata!";
shift
done

Thanks to george9233 for the beginning of this script.

That was fun! But the really easy version is
sudo apt-get install trash-cli
man trash