Reputation: 969
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
Upvotes: 4
Views: 19966
Reputation: 111
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
Upvotes: 11
Reputation: 185025
What I would do :
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
exit_code=$?
if [[ $exit_code != 0 ]]; then
echo "sftp error" >&2
exit 1
fi
echo "sftp end" >> /test/logfile.log
Upvotes: 4
Reputation: 12438
Instead of using sftp
and writing so many intermediate commands in order to move to the proper folders, remove files etc before your transfer, you could use the following way more compact commands:
echo "file transfer started" >> /test/logfile.log
ssh user@server 'rm /tgt/files/*.csv' >> /test/logfile.log 2>&1 && scp /src/files/*.csv user@server:/tgt/files/ >> /test/logfile.log 2>&1
rc=$?
if [[ $rc != 0 ]]; then
echo "ERROR: transfer failed" >> /test/logfile.log
exit 1
fi
echo "file transfer completed" >> /test/logfile.log
Explanations:
ssh user@server 'rm /tgt/files/*.csv' >> /test/logfile.log 2>&1 && scp /src/files/*.csv user@server:/tgt/files/ >> /test/logfile.log 2>&1
if the files are properly removed from the target folder than and only than (&&
) the transfer will be done!! Intermediate errors are also redirected to the output log files.
Upvotes: 1