How can I use `ls -d` in SFTP?

1

From this Question I know that I can run ls -d to show the directory names only instead of their contents.

Short question:

How to do the same with sftp.

Specific problem:

I have a script which should gather directories:

echo ls -1 '*/*/Folder*' | sftp -i /path/to/key user@host

If there is more than one folder matching, I receive a list of the folders:

path/to/Folder1
path/to/Folder2
[...]

If there is only one folder matching, I receive the contents of that folder:

path/to/Folder1/File1
path/to/Folder1/File2
[...]

But I'd like to see just this:

path/to/Folder1

Note:

  • I cannot just use ssh -c as I don't have full access.

pLumo

Posted 2017-11-08T09:23:52.960

Reputation: 123

You could add | cut -d / -f 2 | uniq to your script to only get the uniques. – Mikael Kjær – 2017-11-08T09:38:34.107

I need the full path, so that does not work. But good idea. This works: | sed -e 's/\/[^\/]*$//' | uniq because folders will always have a trailing / and I have no folders below. It's somehow a dirty workaround though... Any better solution? – pLumo – 2017-11-08T09:42:11.540

I think everything is going to be a workaround. At least I see nothing in the ls included in sftp which can help you.

– Mikael Kjær – 2017-11-08T09:53:04.203

Answers

1

When running ls in sftp, you are not running the system executable ls, but a stripped down version included as an internal command of the sftp environment. The -d option is not supported by this version since it isn't the actual ls you are familiar with,and only supports a limited set of options (see help in the sftp environment):

ls [-1afhlnrSt] [path]             Display remote directory listing

So, your only choice is to parse the output:

echo ls -1 '*/*/Folder*' | sftp -i /path/to/key user@host |
    sed -E 's|(.*/Folder*[^/]*/).*|\1|' | grep -v '^sftp' | sort -u

The sed will remove anything after the */*/Folder*/, te grep -v will remove the line showing the sftp prompt and the command run (sftp> ls -1 */*/Folder*/) and the sort -u will only show unique entries.

terdon

Posted 2017-11-08T09:23:52.960

Reputation: 45 216