Assuming that you are trying to run a shell script to gain access through a system through SSH then if that connection is successful to run a command. To do this there are multiple things you could do that are much simpler than trying to make an interpret less language work. What I would strongly suggest is that to solve the first issue is to make a smaller script within the script. Such as doing something like this:
ssh user@known_address << EOF
- This will start the session and keep everything running beneath it until it reaches the term EOF
Using this may help you later if you are in the Linux industry as well. The script should look something like this:
ssh user@known_address << EOF
scp /etc/passwd USER@your_address/Path
EOF
- keep note that this is an example of what you can do but it is not very wise to keep extra copies of the password file laying around on other systems.
Then instead of using exact copies of what the system outputs you can simply use exit codes. This can be WAY more helpful along the way. You can receive the error codes of the last command you ran with echo $?
I cannot guarantee that this script will work but here's an example of what you can do
session() {ssh user@add << EOF; command1; command2; command3; EOF}; session; if $? == 1; echo "test failed".
Sources
https://www.shellhacks.com/ssh-execute-remote-command-script-linux/
Meaning of exit status 1 returned by linux command
https://www.shellscript.sh/functions.html