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 /.

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.