FTP exit and error codes

I have a script which connects to a remote server via FTP and gets some file from there.

#!/bin/bash
/usr/bin/ftp -n remote.hostname.com <<EOF
quote USER user123
quote PASS password123
lcd /dir1/dir2/dir3
cd /
mget file_pattern*
close
bye
EOF

rc=$?
            if [[ $rc != 0 ]]
            then
            echo "Error occured getting the files...$rc" `date "+%Y-%m-%d-%H.%M.%S"`
            exit 1
else
  echo "Successful transfer of the files...$rc" `date "+%Y-%m-%d-%H.%M.%S"`
fi

When the files with the mentioned patterns are not available on the server, the script should echo the failure message and exit the script with error code 1, else it should download the files and echo the successful transfer message. However, in my case, it is always returning the successful transfer message even if there are no files on the server with that name. Any suggestions on what needs to be changed?

You may have to check the text printed by FTP.

I did echo $rc and it was returning '0' . I believe it is returning this after successfully completing the close and bye commands. But, how can it return an error code or exit code as '1' in case there are no files to download or any issues with downloading? Any suggestions?:confused:

You might have to check the text printed by ftp (which is not the same thing as the return code).

Okay, I checked what FTP command from the script gives the output. It is as below

Local directory now /dir1/dir2/dir3
No files found.
0
Successful transfer of the files...0 2014-06-24-12.19.19

If this is not what you were referring to as text, please let me know how can I find it.

OK, something like:

ftp <<EOF 2>&1 > /tmp/$$
...
EOF

if [ "$?" -ne 0 ] || grep "No files" /tmp/$$ >/dev/null
then
        echo "Error in file transfer"
fi

rm -f /tmp/$$

I suspect that FTP will still return nonzero error codes for things like failure to connect, so it checks both.

1 Like

FTP almost always returns 0. The return code is not normally useful.
You have to parse the responses from an ftp server to figure out what is going on. A 3 digit number is first followed by text. Every transaction gets one of the things.

FTP return codes are displayed like: 550 Failed to connect

List of FTP server return codes - Wikipedia, the free encyclopedia

See also: FTP

1 Like

Thank you. I will have to do more digging I guess to implement this right... Or, I will add one more code to check the number of files downloaded in the destination after the FTP script gets completed.