give rm a new undo!
December 4th, 2006 by Lawrence David
i can now rm with impunity, thanks to the code snippet i’ve inserted into my ~/.profile:
alias rm=’safe_rm.sh’
where ‘safe_rm’ refers to this wonderful piece of code i found on the interwebs some months ago [download safe_rm if too lazy to copy+paste; don't forget to rename safe_rm.sh]:
#!/bin/sh
for file in $*; do
if [ -e $file ]; then# Target exists and can be moved to Trash safely
if [ ! -e ~/.Trash/$file ]; then
mv $file ~/.Trash# Target exists and conflicts with target in Trash
elif [ -e ~/.Trash/$file ]; then# Increment target name until
# there is no longer a conflict
i=1
while [ -e ~/.Trash/$file.$i ];
do
i=$(($i + 1))
done# Move to the Trash with non-conflicting name
mv $file ~/.Trash/$file.$i
fi# Target doesn’t exist, return error
else
echo “rm: $file: No such file or directory”;
fi
done
now, removes don’t delete permanently; they simply move targeted files or directories to my trash bin.
also in the name of keeping the kid gloves on when i’m in the terminal, i’ve added these other lines to my ~/.profile:
alias cp=’cp -i’
alias mv=’mv -i’
now, the terminal asks for my confirmation before cp or mv are used to overwrite any files.
awesome! i am constructing a small shrine to you in my nook.
no spicy offerings please.
Note: in the .profile I had to use
alias rm=’sh safe_rm.sh’
otherwise you coudl try to make it executable by chmod the permissions or possibly call it locally with ./safe_rm.sh. I did not try either of the following.
This will break for files with spaces in the names. It’s simply a matter of adding quotes around variables in many places. The trickiest one is the first:
for file in $*; do
should be (though I think it may require bash instead of sh)
for file in “$@”; do
The following naive quoting breaks because it treats all the arguments as one big argument.
for file in “$*”; do
awesome — thanks ivan!!