One solution would be having prepared statements for shell commands instead of doing those risky string concatenations.
And I have stopped using rm to delete files because this command is way too stupid and can take options from file-names.
I use find command,
run it dry once to show what is found
then run find stuffs-to-trash -delete