Thursday, July 3, 2008

Go easy on "rm -fr"

Here I am trying to improve and extend an old script that read:
#!/bin/bash

[ ! -d ~/stage ] && exit 1

(cd ~/stage; rm -vfr *)

...
The new version read:
#!/bin/bash

STAGE=$HOME/stage

[ ! -d "$STAGE" ] && exit 1

(cd $STAGE; rm -vfr *)

...
Guess what? I managed to wipe out a good chunk of my $HOME!!

The explanation is that (cd $STAGE; rm -vfr *) executes in a new (child) copy of the shell [I wrote the code like this so I don't have to cd back after the removal].

The STAGE environment variable is set in the parent shell but is not inherited by the child shell because I did not export it so what got executed was in fact (cd; rm -vfr *) [just saying "cd" in bash gets you back to your $HOME].

The proper way to do this was:
#!/bin/bash

STAGE=$HOME/stage; export STAGE;

[ ! -d "$STAGE" ] && exit 1

(cd $STAGE; rm -vf *)

...
Note that I added the export STAGE statement and dropped the "-r" from the remove command as I really had no sub-directories in ~/stage

-ulianov