SFTP: get back the number of files in a remote directory?
I have sent a batch of files to a remote server via SFTP. If it was a local directory, I could do something like this ls -l | wc -l
to get the total number of files. However with SFTP I am getting an error Can't ls: "/|" not found
.
echo ls -l | sftp server | grep -v '^sftp' | wc -l
If you want to count the files in a directory, put the directory path after the ls -l command, for example
echo ls -l /my/directory/ | sftp server | grep -v '^sftp' | wc -l
Use a batch file to run commands remotely and return data to work in bash:
Create a batch file named mybatch.txt
with these sftp commands:
cd your_directory/your_sub_directory
ls -l
Save it and give it 777 permissions.
chmod 777 mybatch.txt
Then run it like this:
sftp your_username@your_server.com < mybatch.txt
He will prompt you for a password, enter it.
Then you will get the output dumped to the bash terminal. Therefore, you can pass this value wc -l
like this:
sftp your_user@your_server.com < mybatch.txt | wc -l
Connecting to your_server.com...
your_user@your_server.com password:
8842
8842 is the number of rows returned ls -l
in this directory.
Instead of linking it to wc, you can send it to a file for parsing to determine how many files / folders.
I would use the sftp batch file. Create a file called batchfile and enter "ls -l" into it. Then run
sftp -b batchfile user@sftpHost | wc -l
The easiest way is to use the command lftp
. For example:
lftp -c 'connect sftp://user_name:password@host_name/directory; ls -l | wc-l' > list.txt
In your current folder on your local computer, a file named list.txt
. Works great for me.