How to list files and only files via SFTP?
Use the -q
option to tell sftp
to be quiet, thereby suppressing most of the output you don't care about:
echo "ls *.txt" | sftp -q [email protected]:/path
You will still see the lines for the interactive prompt to which you are echoing, e. g. sftp> ls *.txt
, but those can be filtered out with a grep -v
:
echo "ls *.txt" | sftp -q [email protected]:/path | grep -v '^sftp>'
As an aside, it's probably better practice to use a batch file, and pass it with the -b
parameter to sftp
rather than echo
ing a pipeline into it.
If all you really want to do is get a list of files, this might actually be better served with ssh
than with sftp
(which, after all, is the secure file transfer program):
ssh [email protected] ls -1 /path
Mount the remote directory tree through SSHFS. SSHFS is a remote filesystem that uses the SFTP protocol to access remote files. If the server allows SFTP access, you can use SSHFS (from the server's point of view, it's the same thing). On the client side, you need to be authorized to use FUSE, which is the case on most modern unices.
Once you've mounted the filesystem, you can use all the usual commands without having to care that the files are actually remote.
mkdir host-dir
sshfs user@host:/dir host-dir
echo host-dir/*.txt
…
fusermount -u host-dir
sftp -q user@host:/dir <<<"ls *.txt" | grep -v '^sftp>`
But that will work only if sftp is not asking by password. Because of grep -v that will affect sftp on asking by password.
But i think it is a lot of times simple if using tail.
sftp -q user@host:/dir <<<"ls *.txt" | tail -n+2