Get the latest file from a remote server from an F

2020-02-06 11:20发布

问题:

I need to get a file from a remote host in Unix. I am using the ftp command. The issue is I need the latest file from that location. This is how I am doing it:

dir=/home/user/nyfolders
latest_file=$(ls  *abc.123.* | tail -1)
ftp -nv <<EOF
open $hostname
user $username $password
binary
cd $dir
get $latest_file
bye
EOF

But I get this error:

(remote-file) usage: get remote-file [ local-file ]

I think the way I am trying to get the file from within the ftp command is incorrect, can someone please help me out?

回答1:

You cannot use shell features, like aliases, piping, variables, etc, in ftp command script.

The ftp does not support such advanced features using any syntax.

Though, you can do it two-step (to make use of shell features between the steps).

First get a listing of remote directory to a local file (/tmp/listing.txt):

ftp -nv <<EOF
open $hostname
user $username $password
cd $dir
nlist *abc.123.* /tmp/listing.txt
bye
EOF

Find the latest file:

latest_file=`tail -1 /tmp/listing.txt`

And download it:

ftp -nv <<EOF
open $hostname
user $username $password
binary
cd $dir
get $latest_file
bye
EOF


标签: unix ftp