I am really not a fan of all this logic being in the shell command.  Our best option is probably to move it into an script (maybe the cartridge sdk) and source it in to the shell command and call functions.  The logic being anything this complex is bound to change and we can't easily make those changes to existing jenkins jobs.