Sign up ×
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 <<EOF
lcd /dir1/dir2/dir3
cd /rsdir1/rsdir2/rsdir3
get file_pattern`date -d "last month" +%m%Y`.csv
        if [[ $rc != 0 ]]
        echo "Error occured getting file and the script abended with error code $rc" `date "+%Y-%m-%d-%H.%M.%S"`
            exit 1
    echo "Successfully transferred the file" `date "+%Y-%m-%d-%H.%M.%S"`

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
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:… –  slm Apr 25 '14 at 20:52

2 Answers 2

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$file

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

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 '14 at 20:43

Try the following:

/usr/bin/sftp -b - <<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|improve this answer
since you mention your system, what version of sftp do you have installed? –  hildred Apr 25 at 2:15

Your Answer


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.