Not able to capture sftp error in Korn Shell

I am not able to capture error condition in sftp in Korn Shell

#!/bin/ksh
sftp  batch@uat >abc 2>&1 << ENDFILE
   cd public
   put /data/WELCOME_55
ENDFILE
ret_val=$?
if [[ $ret_val -eq 0 ]]
then
   print file "copied successfully"
else
   print file "NOT copied successfully"
fi
return 0

Now the file /data/WELCOME_55 does not exist. I am seeing the error message in file abc. But ret_val is zero.

Any help?

Thanks - Soham

I couldn't get it to work, either.

Maybe you could check if the file exists after SFTP is done?

if [ -f filename ]; then
  ...
else
  ...
fi

Yes that will work if the file does not exist in destination server. If it exists and the sftp has failed, still we will get SUCCESS messaage.

Try running sftp in batch mode...see man pages, should return 1 in this case. Also try running sftp in verbose modes so you see the nature of the failure.

1 Like

Oh yes, I saw that but didn't think to test it. Shows how much I use SFTP :smiley:

I have tried that also. But no success.

Having read the man page, I'd assume that would work.

Here's what I use!

$ ssh someone@somewhere '[ -f /tmp/temp.txt ] && cat /tmp/temp.txt || exit 1' > temp.txt  
$ echo $?
1

$ ssh someone@somewhere 'touch /tmp/temp.txt'

$ ssh someone@somewhere '[ -f /tmp/temp.txt ] && cat /tmp/temp.txt || exit 1' > temp.txt  
$ echo $?
0

I am using below code, please check, output also mentioned.

script.sh

sshpass -p password sftp username@server.com  << ENDFILE
cd httpdocs
put test.php
ENDFILE

if [[ $ret_val -eq 0 ]]
then
   echo "file copied successfully"
else
   echo "file NOT copied successfully"
fi



# sh script.sh
Connected to server.com.
sftp> cd httpdocs
sftp> put test.php
Uploading test.php to /var/www/server.com/httpdocs/test.php
file copied successfully

The problem is what to do when the file is not copied.

BTW, I don't see where you set ret_val :slight_smile:

I am sorry scott, i miss the part.


script.sh

sshpass -p password sftp username@server.com  << ENDFILE
cd httpdocs
put test.php
ENDFILE

ret_val=$?
if [[ $ret_val -eq 0 ]]
then
   echo "file copied successfully"
else
   echo "file NOT copied successfully"
fi