I have the snippet below inside my ksh script. Is there a way that I can have a return code whether the sftp executed successfully and copied the files from source to target destination?
echo "sftp start" >> /test/logfile.log
sftp user@server <<EOF >> /test/logfile.log
cd /tgt/files
lcd /src/files
rm *.csv
put -p *.csv
exit
EOF
echo "sftp end" >> /test/logfile.log
The solution of Gilles Quenot will only work with the following three improvements. Without those improvement the exit status will always be 0 regardless the result of the sftp commands.
sftp option -b -
needs to be added to the sftp command. Only then will sftp exit with status 1 if some sftp command goes wrong. Otherwise the exit status is always 0.
I've added 2>&1 | tee
to log also the errors (it redirects stderr to stdout)
You must use ${PIPESTATUS[0]}
to read the exit status of sftp. $? gives the exit status of the last command and that is the redirect to the logfile.
echo "sftp start" >> /test/logfile.log sftp -b - user@server <<EOF 2>&1 | tee /test/logfile.log cd /tgt/files lcd /src/files rm *.csv put -p *.csv exit EOF exit_code=${PIPESTATUS[0]} if [[ $exit_code != 0 ]]; then echo "sftp error" >&2 exit 1 fi echo "sftp end" >> /test/logfile.log
Regards, Maarten
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With