Save a list of files over SFTP to a text file

The sftp command is very limited. If you can't make it do what you want, you can use another approach, which is to mount the remote directory with the SSHFS filesystem. SSHFS uses SFTP as the transport protocol, so the server side just sees an SFTP client. You need to be able to use FUSE on the client side.

With SSHFS, you mount the remote directory onto an existing, empty directory and use ordinary commands.

mkdir remote
sshfs "$remotehost:$remotelocation" remote
cd remote

echo *.* >"$localpath/dirlist.txt"

fusermount -u remote
rmdir remote

This works by far the best:

echo 'ls' | sftp hostname

You can forward the output into a file by

echo 'ls' | sftp hostname > /tmp/mylist.txt

The dir command within the sftp client does not support redirection. Example below, showing how it does nothing.

sftp> pwd
Remote working directory: /var/tmp/foodir
sftp> lcd /var/tmp/foodir
sftp> dir *.*
foo.txt
sftp> dir *.* >dirlist.txt
foo.txt
sftp> dir
foo.txt
sftp>

Man page for sftp confirms.

ls [-1afhlnrSt] [path]

    Display a remote directory listing of either path or the current directory if path is not specified.  path may contain glob(3) characters and may match multiple files.

    The following flags are recognized and alter the behaviour of ls accordingly:

    -1

        Produce single columnar output.
    -a
        List files beginning with a dot (‘.’).
    -f
        Do not sort the listing. The default sort order is lexicographical.
    -h
        When used with a long format option, use unit suffixes: Byte, Kilobyte, Megabyte, Gigabyte, Terabyte, Petabyte, and Exabyte in order to reduce the number of digits to four or fewer using powers of 2 for sizes (K=1024, M=1048576, etc.).
    -l
        Display additional details including permissions and ownership information.
    -n
        Produce a long listing with user and group information presented numerically.
    -r
        Reverse the sort order of the listing.
    -S
        Sort the listing by file size.
    -t
        Sort the listing by last modification time.