Reputation: 33
Shell script for file transfer by SFTP is already written and working fine on AIX Version 6.1. I am developing ETL with SAP Data Services and real new to shell scripting. During unit testing, I provided non-existent target folder for SFTP to simulate a case if target folder name was changed by a user, but it did not fail after command cd and returned exit code 0, though echoing error message: Couldn't canonicalise: Failure. That makes ETL process not aware that file was not transferred. When I injected exit 1 in script, the ETL job caught the SFTP failure and failed itself, which is an expected behaviour.
My question is: How can I tweak existing shell script invoking SFTP command to exit with code 1?
Here is excerpt from script:
'#!/bin/sh
....
echo cd $TARGET_REMOTE_DIR>>$INPUT_FILE
echo put $TARGET_LOCAL_DIR$TARGET_FILE_NAME>>$INPUT_FILE
echo quit>>$INPUT_FILE
/usr/bin/sftp -b $INPUT_FILE $USER@$HOSTNAME
I echo
$?
variable right after command cd
, it returns 0 when remote dir is spelled wrong. What I am thinking is probably checking in-line for existence of an error message after command cd
and if its length is not 0 then exit with code 1.
Something like in pseudo code:
error_msg = get_error_msg({cd $TARGET_REMOTE_DIR>>$INPUT_FILE})
if length(trim(error_msg)) <> 0 then
echo “Cannot change directory! Aborting…”
exit 1
fi
Any comments are appreciated.
Cheers!
With great help from Martin I have implemented this solution: Catching $? return code right after command /usr/bin/sftp and forcing to exit with caught error!
/usr/bin/sftp -b $INPUT_FILE $USER@$HOSTNAME
if [[ $? -ne 0 ]]; then
" SFTP Error while accessing remote target directory! Error message"
exit $?
fi
Thank you all! Great forum!
Upvotes: 3
Views: 7373
Reputation: 202222
First, I assume, you are using OpenSSH sftp
.
The OpenSSH sftp
indeed aborts the script and exits with 1
, when cd
command fails.
So you problem is probably not with the SFTP script, but in a way you capture the exit code.
If you share details, how you capture the exit code, you may get more concrete answer.
As for your test with echo $?
:
Where do you put echo $?
command? To your SFTP script ($INPUT_FILE
)? sftp
does not have an echo
command; and it cannot resolve $?
either.
If you put it to the shell script like this:
echo cd $TARGET_REMOTE_DIR>>$INPUT_FILE
echo $?
it does not do, what you want. You are here just querying result of previous echo
command, which is unlikely to ever fail.
Upvotes: 1