closing a telnet session on error, in a shell script

I am using a shell script to telnet into a remote unix server and execute certain commands. But if any command being executed remotely, throws an error, the script just hangs. And the telnet session does not get closed.

I want to be able to close the session and complete the script execution in case of an error or otherwise.

Below is the script. Any help will be appreciated.
#!/bin/sh
( echo open host
sleep 1
echo user
sleep 5
echo pswd
sleep 4
sourceDir=$1 ; filename=$3 ; destDir=$2
echo "cd ${sourceDir}"
sleep 1
echo "cp -rf ${filename} ${destDir} && \
cd ${destDir} && \
$cmd ; exit"
) | telnet

I also want to be sure the previous command got executed before proceeding to execute the next command, which is why I'm using '&&'. This, not by using "sleep", but some other way of ensuring the earlier command did get executed successfully.

The above script cribs at the echo of the last command. Snippet of the error is

uctvd201:/opt/epds/EPDSDV01/epdata/SPONSOR/0000_071/test [EPDSDV01]# d && \ <
sh: : Execute permission denied.
uctvd201:/opt/epds/EPDSDV01/epdata/SPONSOR/0000_071/test [EPDSDV01]# ad && \ <
sh: : not found.

Not sure how much help I am since scripting is not one of my strong points, but I do notice some things.

I don't personally use telnet...it's a security hole unless you only have it open on a private subnet...even then...ssh is better.

I notice your script uses the sleep command in places where it should be waiting for user input. There is different shell scripting command that waits for user input instead of the sleep command...I believe it's the "read" command.

Just from the error snippets you posted, whatever user you're logging in as doesn't have the proper permissions to do what you want. Unless you're logging in as root (not good through telnet)...you need to use sudo.

If you want to make sure the previous command was successful...you're going to need to use if - else statements.

I wish I was better at scripting because I know exactly how to fix your issue I just don't know the proper syntax. Hopefully I've given you enough clues that you can get it figured out on your own. You seem to have good enough knowledge to do it.