Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Return Code of SFTP command

Tags:

unix

ksh

sftp

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
like image 711
mtryingtocode Avatar asked Sep 15 '25 09:09

mtryingtocode


1 Answers

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.

  1. 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.

  2. I've added 2>&1 | tee to log also the errors (it redirects stderr to stdout)

  3. 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

like image 97
maderkse Avatar answered Sep 18 '25 09:09

maderkse