6

I can list file names actually but a lot of unwanted stuff comes from there also.

> echo "ls *.txt" | sftp user@host:/dir
Connected to 1.1.1.1.
Changing to: /dir
sftp> ls *.txt
1.txt
2.txt
3.txt

Is there a proven/reliable way to list files and only files? I'd like to avoid using head-like filters if possible.

5

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 user@host.example.com:/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 user@host.example.com:/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 echoing 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 user@host.example.com ls -1 /path
2
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 
  • The OP specifically says 'I'd like to avoid using head-like filters if possible.'. tail is about as head-like as you can get without using head. – DopeGhoti May 25 '16 at 17:46
  • Ok corrected now. – Luciano Andress Martini May 25 '16 at 17:49
2

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
  • sshfs is a great tool, it works for me. – lutaoact Apr 19 '17 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.