Executing script on device shutdown
Our default answer on questions like this is tasker – whenever it comes to automation, this is the most powerful tool to be mentioned. Tasker combines Contexts (Events, states, location, time) with Tasks to be fired when such a context is met. For your case, there's an event called Device Shutdown – which you could combine with the task Code › Run Shell to execute your shutdown scripts.

For further reading, I strongly recommend you visiting our tasker tag-wiki, which also links to additional resources like the tasker user-guide or my collection of tasker resources.