Set the state at the top
Resolve paths, check arguments, and set the options that make it stop on failure, all before any work begins. A script whose setup is visible in the first ten lines can be reviewed without running it.
Write to a temporary place then move
Build the output in a temporary folder and move it into place at the end. If the run fails halfway, the previous good output is still there, which is the difference between a broken deploy and a half written one.