You need code tags, your post is hard to read
Start with only the sql, run it from the sqlplus prompt.
Next wrap JUST the sql that ran above in a shell wrapper. Execute it. Use the parameter associated with the problem.
One thing I've seen that causes hangs is the sqlplus gets what it thinks is garbage, usually caused by trying to quote or escape something so the shell will not wreck it, and passing it through the shell script to sqlplus. sqlpus hangs because it is waiting for more input, like to complete the quote for example.
As a first guess consider this is your problem, especially since it is intermittent. Intermittent == parameter problems
It a is a wait on stdin for sqlplus, I believe.