Scripts triggered via 'expect' - stderr lost

I have a bash script on server that runs fine when run interactively and writes stderr output to a file.

However, when invoked through a 'expect' script run on Mac OS my laptop which does ssh to the server : generates the expected file, but file has no content. I suspect the stderr is getting lost somewhere in bash or in 'expect'.

My 'expect' script (run from Mac OS) :

/usr/bin/expect -f - <<EOD
spawn ssh -t myUserName@theServer
expect "myUserName@theServer:~> " { send "sudo -su adminRole\r" }
expect "myUserName's password:" { send "myUserNamePassword^\r" }
expect "adminRole@theServer:/home/myUserName" { send "the_script.sh\r" }
EOD

the_script.sh (residing on remote SuSE server):

#!/bin/bash
/usr/bin/java -cp '/some/lib/lib.jar' -Dproperties=some_app.properties com.example.MyApp 2>output.txt

Note :
I only have myUserName account on theServer and have been granted the 'adminRole' to perform specific tasks, one of which is running the MyApp java program & looking at its output (monitoring). This program writes its output to stderr stream instead of stdout, for reasons I do not know , nor can I change it. Also, the lib.jar location is only available as adminRole, so I cannot execute the script as myUserName without doing a sudo.

I have copied my ssh key to server so I can login myself (as myUserName) by password-less login. However, for doing 'sudo' I have to resort to the above 'expect' script.

Now, when I ssh from Mac OS native terminal to theServer, do a 'sudo -su adminRole', and then run the_script.sh , I correctly get the output.txt file with java program's output.
On the other hand, when I run the above 'expect' script from Mac OS terminal , it does login to theServer and create the output.txt file , but the file is empty.

Since I'm really having remote script itself direct output to a file, I suspect this is not a problem with 'expect' itself.

I realize embedding password in script is not good , but for certain reasons, it is acceptable for the time being. I contemplated getting access to resources to myUserName , so that the sudo juggling is avoided, but that is not an option for bureaucratic reasons beyond my control.

Can anyone point what may be wrong in my script ? I've tried to google a lot around 'expect' and how sudo works, but in vain.

I hope so. This:

[...]App 2>output.txt

means the output is locally(!) put into a file "output.txt" in whatever happens to be the current directory. Might it be that the file is not "created" empty, but simply not in the place where you look?

It might be a good idea to put a fixed path in front of the filename to remove any ambiguity:

[...]App 2>/path/to/output.txt

You might start with "/tmp" and - if you need to keep several versions of this file - qualify the name with a date- and/or time-extension, like this, see man date for appropriate format descriptors:

[...]App 2>/path/to/output.$(date +'%Y%m%d').txt

I hope this helps.

bakunin