Unable to get the right exit code from a script

6,567

Solution 1

You got the right return code, sftp session executed correctly so the return code is 0.
You should use scp instead, it does not returns 0 if it fails to copy.

You could do something like :

file=file_pattern`date -d "last month" +%m%Y`.csv 
[email protected]:/rsdir1/rsdir2/rsdir3/$file
local=/rsdir1/rsdir2/rsdir3/$file

if scp -q $remote $local
then
    echo "Successfully transferred the file" `date "+%Y-%m-%d-%H.%M.%S"`
else
    echo "Error occured getting file and the script abended with error code $?" `date "+%Y-%m-%d-%H.%M.%S"`
    exit 1
fi

EDIT: I changed the copy target to a file name : If you copy to a directory and that directory is missing, you will create a file that has the directory name.

Solution 2

Try the following:

/usr/bin/sftp -b - [email protected] <<EOF ...

The "-b -" puts sftp in batch mode while still reading from the command line. Batch mode will (on my system) exit sftp and return a non-zero exit code when one of the sftp commands fails.

Share:
6,567

Related videos on Youtube

Dhruuv
Author by

Dhruuv

Updated on September 18, 2022

Comments

  • Dhruuv
    Dhruuv over 1 year

    I have a script which connects to a remote server via SFTP and get some file from there. My script goes like this:

    /usr/bin/sftp [email protected] <<EOF
    lcd /dir1/dir2/dir3
    cd /rsdir1/rsdir2/rsdir3
    get file_pattern`date -d "last month" +%m%Y`.csv
    EOF
    rc=$?
            if [[ $rc != 0 ]]
               then
            echo "Error occured getting file and the script abended with error code $rc" `date "+%Y-%m-%d-%H.%M.%S"`
                exit 1
        else
        echo "Successfully transferred the file" `date "+%Y-%m-%d-%H.%M.%S"`
            fi
    

    However, even if the script doesn't find the file with the pattern it goes to the else part of the script and gives me the output on the screen as

    Connecting to remote.server.com...
    sftp> lcd /dir1/dir2/dir3
    sftp> cd /rsdir1/rsdir2/rsdir3
    sftp> get file_pattern032014.csv
    Couldn't stat remote file: No such file or directory
    File "/rsdir1/rsdir2/rsdir3/file_pattern032014.csv" not found.
    Successfully transferred the file YYYY-MM-DD-24HH.MI.SS 
    

    Any advices on what I might be doing wrong here?

    • slm
      slm about 10 years
      You might want to take a look at lftp too instead of trying to script with sftp. It's not really meant to be used in that fashion. I show an example doing something like this using lftp here: unix.stackexchange.com/questions/88710/…
  • Dhruuv
    Dhruuv almost 10 years
    Quick question, I am having the same trouble with pulling the file (here, I have a file name pattern instead of exact file name) using FTP script. Any recommendations from your side on this? Or should this be posted as a different question? Not sure. please advise.