Nap
Nap

Reputation: 8276

Simple sftp get causes error sometimes

I would like to get an opinion on checking the error of a shell script. The system that I am supporting contains a simple shell script that is run multiple times by another application (a java). The java calls a shell script that performs ftp connection open, moving the local directory, mget command and finally a bye command. It then checks the $? after the bye command.

I know that in the first place this code is suspicious since it should only check the bye command always but it intermittently causes an error. I already ask the UNIX admin to see if there are log error in the system, but they said there is non.

Basically the script general structure is:

sftp -oPort=<port forwarding port> <ip and user> <<==
lcd <some variable>
mget <some variable>
bye

rtn=$?
if [ ${rtn} != 0 ]
then
        exit 1
fi

exit 0

any ideas why the $? returns a non zero at times?

Upvotes: 0

Views: 3930

Answers (1)

Anya Shenanigans
Anya Shenanigans

Reputation: 94654

Reasons for a non-zero exit code:

  1. The lcd command failed and you're in batch mode
  2. The mget command failed (the glob did not work) and you're in batch mode
  3. The bye command failed (low probability) and you're in batch mode
  4. There was no sftp server on the remote end (exit code == 255)

If you want to deliberately ignore errors from commands being used, then you can prefix the command with - e.g. mget becomes -mget

An important thing to do when trying to debug this is to capture the output of the command and dump it when the command fails e.g.

trap 'rm -f /tmp/logfile.$$' EXIT HUP
sftp -oPort=<port forwarding port> <ip and user> >&/tmp/logfile.$$ <<EOM
lcd <some variable>
mget <some variable>
bye
EOM
rtn=$?
if ((rtn != 0)); then
    cat /tmp/logfile.$$
    exit 1
fi
exit 0

The trap deletes the file when the script terminates.

Upvotes: 3

Related Questions