How to stop a running shell script if it executes some dangerous operations?

milkice asked:

I mean, how to dynamically stop a running shell script based on what operation it’s doing. Because some dangerous commands such as rm, if using regex before running, some edge situations may escape, like

#!/bin/bash
name=""
$name rm a.py

will still remove a.py.

So is there a way to detect what the next command is of a running script and stop it if matches.

Maybe complex regex can do this before running, but I want to know if there is a nice solution with running scripts.

My answer:


You can quote the variable in double quotes. If the variable is empty, bash will throw an error:

#!/bin/bash
name=""
"$name" rm a.py

results in:

bash: : command not found

If the variable has content, then it will be treated as you would expect:

#!/bin/bash
name="echo"
"$name" rm a.py

gives the output on screen:

rm a.py

because it runs "echo" rm a.py.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.