trash

A script similar to the recycle bin feature on windows platforms. It moves files/directorys to a defined directory instead of removing them from the filesystem. If you really want to get rid of them, you can use the $trash/empty command.

Installation / Usage

  1. Copy trash & maketrash to a path that is included in $PATH.
  2. Set $trash to your trash path: e.g. export trash=/trash1).
  3. Run maketrash.
  4. Now you can use trash <directory/file> instead of rm.
  5. To restore directorys/files goto $trash (cd $trash/<date>)
  6. Empty trash via $trash/empty

Downloads

Source Code


trash
#!/bin/bash
 
# trash
# A script similar to the recycle bin feature on windows platforms.
# It moves files/directorys to a defined directory instead of removing them from the filesystem.
# If you really want to get rid of them, you can use the $trash/empty command.
 
# Version 0.41 build 180304
# by Heiko Barth
 
# Set your desired date format; See 'man date' for details
today=$(date +%Y-%m-%d)
 
if [ "$trash" == "" ]; then
	echo "Error: \$trash variable not set. Put something similar like 'export trash=/tmp/trash' in your .bashrc and login again." >&2
	exit 1
else
	if [ ! -d "$trash" ]; then
		echo "Error: Run 'maketrash' first." >&2
		exit 1
	fi
fi
 
if [ "$1" != "" ]; then
	for i in "$@"; do
		# Abort if file does not exist and is no symbolic link (there can be symbolic links pointing to files that does not exist)
		if [ ! -e "$i" ] && [ "$(stat -c %F "$i" 2>/dev/null)" != "symbolic link" ]; then
			echo "Error: File/Directory '$i' does not exist." >&2
			fail=1
			continue
		fi
 
		b=$(basename "$i")
 
		# Create target directory
		mkdir -p -m 700 $trash/$today 2> /dev/null
 
		# If target exist, find an alternate name
		if [ -e "$trash/$today/$b" ] || [ -h "$trash/$today/$b" ]; then
			j=0
			while [ 1 ]; do
				let j++
		                if [ ! -e "$trash/$today/$b.$j" ] && [ ! -h "$trash/$today/$b.$j" ]; then
					mv "$i" "$trash/$today/$b.$j" || {
						echo "Error: Could not move '$i'" >&2
						fail=1
					}
					break
				fi
			done
		else	
			mv "$i" "$trash/$today/$b" || {
				echo "Error: Could not move '$i'" >&2
				fail=1
			}
		fi
	done
	[ ! -z $fail ] && exit 1 || exit 0
else
	for i in "$(head -9 $(readlink -f "$0") | tail -7)"; do
		echo "$i" | cut -d ' ' -f 2-
	done
	echo
	echo "Syntax: trash <file/directory>" >&2
	exit 1
fi
maketrash
#!/bin/bash
 
# maketrash: Create trash directory set in $trash; This is where 'trashed' files were move to.
# Version 0.3 build 0802
# by Heiko Barth
 
if [ "$trash" = "" ]; then
        echo "Error: \$trash variable not set" >&2
        exit 1
fi
 
mkdir -p -m 700 "$trash"
 
if [ ! -f "$trash"/empty ]; then
        script=$(readlink -f "$0")
        echo '#!/bin/bash' > "$trash"/empty &&
        echo 'rm -rf "'"$trash"'"' >> "$trash"/empty &&
        echo "$script" >> "$trash"/empty &&
        chmod 700 "$trash"/empty
fi
1)
Consider putting this into your .bashrc or similar