Feed on
Posts
Comments

give rm a new undo!


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.


Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

5 Responses to “give rm a new undo!”

  1. on 04 Dec 2006 at 9:20 pm cubicle_down_the_hallway

    awesome! i am constructing a small shrine to you in my nook.

  2. on 04 Dec 2006 at 9:23 pm Lawrence David

    no spicy offerings please.

  3. on 15 Sep 2007 at 11:03 am D

    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.

  4. on 20 Aug 2008 at 3:37 pm Ivan Andrus

    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

  5. on 21 Aug 2008 at 8:23 am Lawrence David

    awesome — thanks ivan!!

Did I get this wrong? Let me know!

Trackback URI | Comments RSS