All of that looks very wrong. It makes my head spin. There must be a better solution…
Couldn’t you use a real language like Python or whatnot?
For a while now Python has had the very nice ‘subprocess’ module that executes commands and handles arguements without a shell.. making lots of things much simplier. Also can handle redirecting stdin, stdout, stderr easy.
For example I use it to deal with situations were I may run into maliciously created file names. With bash or shell environments the only effective way to deal with potentially malicious filenames is to use nulls for line seperators, but only a few commands (like find, sort, xargs) support it and you only see that support in GNU extentions so they are very non-portable.
But with subprocess I can pass all sorts of crappy filenames, including file names with newlines or other characters that have significance in a shell environment, directly to commands as arguements and so far everything handles it quite well.