Deleting Files Using an Empty Variable
Problem
You have a variable that you think contains a list of files to delete, perhaps to clean up after your script. But in fact, the variable is empty and Bad Things happen.
Solution
Never do:
rm -rf $files_to_delete
Never, ever, ever do:
rm -rf /$files_to_delete
Use this instead:
[ "$files_to_delete" ] && rm -rf $files_to_delete
Discussion
The first example isn’t too bad, it’ll just throw an error. The second one is pretty bad because it will try to delete your root directory. If you are running as a regular user (and you should be, see Running As a Non-root User), it may not be too bad, but if you are running as root then you’ve just killed your system but good. (Yes, we’ve done this.)
The solution is easy. First, make sure that there is some value in the variable you’re using, and second, never precede that variable with a /.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access