Detecting upload success/failure in a scripted command-line SFTP session?

Solution 1:

If you batch your SFTP session, the exit status $? will tell you if it's a failed transfer or not.

echo "put testfile1.txt" > batchfile.txt
sftp -b batchfile.txt user@host
if [[ $? != 0 ]]; then
  echo "Transfer failed!"
  exit 1
else
  echo "Transfer complete."
fi

Edited to add: This is something we use in a production script at work, so I'm sure it's valid. We can't use scp because some of our customers are on SCO Unix.

Solution 2:

It is the tradition of serverfault not to unduly question the preconditions, but I have to ask: is it not possible for you to either 1) mount the remote filesystem via SMB, or 2) use fuse/sshfs instead? (I assume here that the sending machine is a Linux box as you are using bash and ssh.)

To actually answer your question, I think your problem is simple. Consider:

quest@wonky:~$ false
quest@wonky:~$ if [ $? != "0" ] ; then echo asdf ; fi
asdf
quest@wonky:~$ if [ $? != "0" ] ; then echo asdf ; fi

Try instead like this:

quest@wonky:~$ false
quest@wonky:~$ res=$?
quest@wonky:~$ if [ $res != "0" ] ; then echo asdf ; fi
asdf
quest@wonky:~$ if [ $res != "0" ] ; then echo asdf ; fi
asdf

To explain: your second if statement "if [ $? != "0" ]; then" tests for the exit status of the latest statement, which is no longer sftp, but the previous if statement.

Then I wonder, will sftp really exit with non-zero if it has problems uploading files? Cursory tests indicate mine doesn't.