2

For example I have a script looks like:

for i in */*/
do  
 cd $i
 cp POSCAR.ideal OSZICAR ..
 cd ..
 rm -r */
 cd ../;
done

to remove subfolder of a folder, however with a bit of uncautious, for example, the last ../ is miswritten as ../../, then the whole computer will be erased. Which is extremely bad! So I want to ask is there a method to safely confine the operation range of a terminal so that such tragedy does not appear?

2
  • 4
    man find ; avoid insecure cd in loops -- try to use full paths; use "echo rm ..." before " rm"; use "rm -i" to confirm; don' t root accounts on Fridays...
    – JJoao
    Commented Oct 2, 2015 at 11:38
  • 1
    Like @JJoao says, a script like this is dangerous at best. It needs a lot of error testing and more complete paths to be remotely safe. And, I don't even want to think about what could happen if some of your directory/subdirectory names have spaces in them since the variables aren't quoted! I've never used it, but there is a chroot command that would help, but rewriting the script would be much better.
    – Joe
    Commented Oct 3, 2015 at 22:44

1 Answer 1

1

As @Joe has correctly mentioned in the comment, it is best to rewrite such a dangerous script. However, if you do wish to go ahead with your current script, a rudimentary method is to wrap all your rm operations within if conditions.

So, for example:

if pwd | grep <some-pattern>; 
then rm -r */; 
fi;

You can modify the grep part according to your needs. My point is that just do a simple grep verification before issuing the rm command.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .