Wrap the SQL in a BEGIN / END block and see if that fixes it.
Another approach, and the one I prefer, it to drop the SQL into a stored procedure. That does a number of things. It keeps the SQL out of shell scripts, allow you to tune and debug it much more easily, and simplifies the script since you need only one command on a line to exec the proc.
Regards,
Bill