Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 USER@remote.server.com <<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?

share|improve this question
    
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/… –  slm Apr 25 at 20:52

1 Answer 1

up vote 8 down vote accepted

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 
remote=USER@remote.server.com:/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.

share|improve this answer
    
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. –  Dhruuv May 28 at 20:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.