Search code examples
linuxbashshellftpexit-code

Getting exit status code from 'ftp' command in linux shell


I need to retrive the exit status code from a command line program. No worries, I used $?. But for ftp, even if it doesn't connect, it opens the ftp shell, so I'm not able to understand that the connection haven't take place.

Try this code for understand:

#!/bin/sh

ftp 1234567
OUT=$?
if [ $OUT -eq 0 ];then
   echo "ftp OK"
else
   echo "ftp Error: "$OUT
fi

exit 0

Any help? Thanks Filippo


Solution

  • You should be looking for success message from ftp command rather than looking for a status. It's "226 Transfer complete". You can confirm it with ftp manual on your system.

    200 PORT command successful.
    150 Opening ASCII mode data connection for filename.
    226 Transfer complete.
    189 bytes sent in 0.145 seconds (0.8078 Kbytes/s)
    

    Here's a sample script.

    FTPLOG=/temp/ftplogfile
    ftp -inv <<! > $FTPLOG
    open server
    user ftp pwd
    put filename
    close
    quit
    !
    
    FTP_SUCCESS_MSG="226 Transfer complete"
    if fgrep "$FTP_SUCCESS_MSG" $FTPLOG ;then
       echo "ftp OK"
    else
       echo "ftp Error: "$OUT
    fi
    exit 0