Converting FTP "ls -ltr" to SFTP

I was migrating an FTP functionality to SFTP. In shell script that does FTP, I saw some lines and I can not convert them to SFTP. I searched but couldn't get a result.

With ftp, I can get remote file names to local log file like this:

ftp>
cd remote_folder
ls -ltr local_file.tmp

With sftp (OpenSSH client) this doesn't work. It says "file could not be found" about ls command. And it also says -t or -r options are invalid with ls command. How can I do same thing with sftp?

Thank you.


Solution 1:

We do not know what "ftp" client you were using. So it's hard to tell what the ls -ltr was doing. Though my guess is that your "ftp" client was transparently passing the switches to the FTP server, not processing them locally. Again, we do not know what FTP server you were using. But I know of only one FTP server that supports -ltr and that is ProFTPD. In ProFTPD the -ltr means long directory listing sorted reversely by timestamp. The OpenSSH sftp client supports the same switches for ls command with the very same meaning. If it is not working for you, you are probably using a very old version of OpenSSH. The -tr switches seem to be supported since OpenSSH 3.6 (February 2001) and the -l even longer.

OpenSSH sftp does not support writing the listing to a file. But you can redirect whole sftp output to a file.

Something like this:

sftp -b script.txt [email protected] > local_file.tmp

With script.txt containing:

cd remote_folder
ls -ltr