The OpenSSH sftp
command has only two exit codes, 0
for success and 1
for failure.
So if you need to distinguish different errors, parsing the command output is your only way.
You can redirect sftp
command output to a temporary file, parse the temp file to find an error message and then print the temp file to output, so that it is included into your log too.
sftp ... > /tmp/sftp.log
grep ... /tmp/sftp.log
...
cat /tmp/sftp.log