Friday, September 11, 2020

Spot the Bug - File Globbing

The bug in this post comes from the world of scripting. Powershell is used for the code below, but this bug could be introduced in any scripting language that is commonly used for task automation. Can you spot the bug?

The code above is a fairly straightforward script. It gets a list of files from fileDir, iterates over each file moving it to two different locations. After looping through the files, it removes the files from fileDir.

The bug in this script is that the removal of the files is done using a wildcard to locate the files to delete. If the number and size of the files being moved is large, the iteration over each file will take some time. New files can be placed in fileDir and those files will be deleted by the final script line using the wildcard. If that scenario happens, data can be lost!

In the code above, the bug is fixed by deleting files by file name as a part of iterating over the list. This approach ensures that you only affect files discovered in the first line of the script, and newly arriving files can't be accidentally deleted.

This example had to be done in Powershell because the C# libraries for working with files and directories don't allow the use of wildcards, therefore preventing a developer from creating this bug. This is another example of the language construct preventing developers from introducing bugs.

No comments:

Post a Comment