How to redirect the output of a command inside ftp block?

hi,

i am using ftp to get files from remote server. inside the ftp i want to us ls -ltr command and send the output of it to a file.

ftp -n remote_server <<_FTP
    quote USER username
    quote PASS password
    prompt noprompt
    pwd
    ls -ltr
    get s1.txt
    bye
_FTP

i want to get the output of only ls -ltr command to be stored in a file and not the other commands like pwd and get.

is it possible to redirect the output of only ls -ltr command into a file.

You can try an expect script for interactive applications like ftp, its possible to capture the output of previous command and direct it to a file.

-Raja

please give me an example using expect and capturing the output of particular command in a file.

This is a basic expect script from which you can start

#!/usr/bin/expect
set timeout 10
spawn ftp -n remote-server
expect "ftp> "
send "quote USER username\r"
expect "ftp> "
send "quote PASS password\r"
expect "ftp> "
send "prompt noprompt\r"
expect "ftp> "
send "pwd\r"
expect "ftp> "
send "ls -ltr\r"
expect "ftp> "
# create the file to write the last command output
set filename "ls-output.txt"
set fd [open $filename "w"]
puts $fd $expect_out(buffer)
close $fd
send "get s1.txt\r"
expect "ftp> "
send "bye\r"
exit

If this is too tricky, you could try this:-

ftp -n remote_server <<_FTP > $LOGFILE
    quote USER username
    quote PASS password
    prompt noprompt
    pwd
    !echo "MARKED START\n"
    ls -ltr
    !echo "\nMARKED END"
    get s1.txt
    bye
_FTP
  • Note, you may need to use !print .... to get the new-line, depending on your OS.

You then will have a section of the output you can retrieve between the marked start & end. If you have the -p flag on grep, this becomes relatively trivial:-

egrep -vp "MARKED START|MARKED END" $LOGFILE 

The -p flag matches a paragraph, so all the output up to the blank line after the "MARKED START" and all the text after the blank before the "MARKED END" will be excluded by the grep -v

Does this help?

Robin