~hacktivista/config

6c8862ee7fdfa778343ae73cd1c8736851c813e5 — Felix Freeman 11 months ago 317a691 master
Safer rm will move files within $HOME to $HOME/.trash
2 files changed, 89 insertions(+), 0 deletions(-)

M root/etc/skel/.bashrc
A root/usr/local/bin/saferm
M root/etc/skel/.bashrc => root/etc/skel/.bashrc +3 -0
@@ 32,3 32,6 @@ cd () {
shpawn () {
    swaymsg exec "\$term --working-directory '$(pwd)'"
}

# Safer rm
alias rm='saferm'

A root/usr/local/bin/saferm => root/usr/local/bin/saferm +86 -0
@@ 0,0 1,86 @@
#!/usr/bin/env sh

# Safer rm.
#
# For files within $HOME it moves files to $TRASH_PATH instead of deleting.
# For files outside $HOME or non-POSIX options (other than -f -i -R -r),
# fallback to `rm`.
#
# The idea is to `alias rm='saferm'`
#
# Use something like
# 0 * * * * find $HOME/.trash/ -prune -ctime +1 | xargs command rm -rf
# in your user crontab to really delete files after 48 hours.
#
# Copyright (c) 2020 Felix Freeman <sir@hacktivista.com>
#
# This software is licensed under the 'MIT No Attribution' license terms. I
# don't want attribution nor exclusive rights over it, but I'd love that you
# free your software too.

TRASH_PATH="$HOME/.trash"

mkdir -p "$TRASH_PATH"

while getopts ':fiRr' opt; do
	case $opt in
		f) flag_forced=1; flags="${flags}f" ;;
		i) flag_interactive=1; flags="${flags}i" ;;
		r|R) flag_recursive=1; flags="${flags}r" ;;
		*) flag_unknown=1
	esac
done

if [ "$flag_unknown" ]; then
	command rm "$@"
	exit $?
fi

shift $(($OPTIND-1))

filepath () {
	if [ "${file:0:1}" != '/' ]; then
		test -d "$1" && cd "$PWD/$1" || cd $(dirname "$PWD/$1")
	else
		test -d "$1" && cd "$1" || cd $(dirname "$1")
	fi

	printf "$PWD/"
	cd - 1>/dev/null
}

for file; do
	case "$(filepath $file)" in
		"$HOME/"*)
			filetype=$(test -d "$file" && echo 'directory' || echo 'regular file')

			if [ ! "$flag_recursive" ] && [ "$filetype" == 'directory' ]; then
				echo "$0: cannot remove '$file': Is a directory" 1>&2
				continue
			elif [ ! -e "$file" ]; then
				echo "$0: cannot remove '$file': No such file or directory" 1>&2
				continue
			fi

			if [ ! "$flag_forced" ] || [ "$flag_interactive" ]; then
				if [ ! -w "$file" ]; then
					nonwriteable=1
					filetype="write-protected $filetype"
				fi
				if [ "$flag_interactive" ] || [ "$nonwriteable" ]; then
					printf "$0: remove $filetype '$file'? " 1>&2
					read confirmation
					test "$confirmation" == 'y' && mv "$file" "$TRASH_PATH"
					continue
				fi
			fi
			mv "$file" "$TRASH_PATH"
			;;
		*)
			if [ "$flags" ]; then
				command rm "-$flags" "$file"
			else
				command rm "$file"
			fi
	esac
done