Well, I’m not a unix expert either, but my guess is that you are trying to write your output.txt file to a location where you don’t have write permission. You might try including the path.
I came up with a test to see where the original code was probably trying to save the file. I used ls, without specifying the directory, to see which directory it would treat as the default.
The result in Terminal is on the left, and the result returned by posixscript( is on the right. Terminal listed the contents of my home directory, and posixscript listed my root directory.
That’s a very useful approach. Using your strategy, I found that both shell- and posixscript will point to the root folder if the path isn’t specified.