I’m working on a script to automate some stuff. The catch with this script is that if any action fails, it needs to “rollback” all the actions it just performed.
After thinking for a bit, I thought instead of having a billion if statements, I would put each command into an array:
CMD[0]='command';
CMD[1]='command';
# ...
Then I could run them in sequence. I would then make another array which had the expected string so I can check against it and see if it worked or not:
So, to run this I would just loop through CMD and for each action, make sure it’s response was EXPECTED, and if not, I stop calling commands and then go back through ROLLBACK in reverse order starting at the index of the last good command.
Does anyone see a problem with this plan? More importantly, does anyone know a better way to do this?
That is a very clever approach. It seems, though, that it would be quite complex to develop.
Another (slight variant) approach would be to write a series of small scripts - each one performs a set of actions. You could call the scripts in sequence, with each returning a success code. If one fails, the “rollback” could be another script that gets called.
As I said, this is simply a variation on your creative idea. But it may prove easier to build, troubleshoot and expand as needed.
As you make progress on this, please post more details. I am VERY curious about your success.