0

I am trying to count the number of files in a remote directory.
I have the following code:

ssh server.com<<RUNTHIS  
 FILE_COUNT=$(ls -AU /foo/bar/test_dir) 
 echo "$FILE_COUNT" > ~/file_count.txt   
RUNTHIS

When I run this I get: ls: /foo/bar/test_dir No such file or directory
But the directory is there. If I do ls /foo/bar/test_dir directly to the server it lists the directory.
Also the following works and saves the contents to the file:

ssh server.com<<RUNTHIS  
 ls -AU /foo/bar/test_dir > ~/file_count.txt
RUNTHIS

What is wrong in the first snippet?

marked as duplicate by Stephen Rauch, Jeff Schaller, G-Man, Romeo Ninov, Philippos Oct 20 '17 at 6:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

It doesn't work because bash will do parameter expansion and command substitution in the heredoc. Try with single quotes around RUNTHIS to protect it.

ssh server.com<<'RUNTHIS' 
 FILE_COUNT=$(ls -AU /foo/bar/test_dir) 
 echo "$FILE_COUNT" > ~/file_count.txt   
RUNTHIS
  • A less weird way to do this would be ssh server.com "ls -AU" > ~/file_count.txt (If I recall how to ssh correctly) – SIGSTACKFAULT Oct 19 '17 at 15:07
  • That won't work for me. I have other commands as part of that block that break if I add the single quote. – Jim Oct 19 '17 at 15:13
  • @Blacksilver: that doesn't do the same thing though, does it. (It writes the file locally and not remotely). – Rastapopoulos Oct 19 '17 at 16:08
  • @Jim: Where does it break if you use single quotes? Could you give an example? – Rastapopoulos Oct 19 '17 at 16:10
  • oh, do you want to write to a remote file? ssh server.com "ls -AU > ~/file_count.txt" – SIGSTACKFAULT Oct 19 '17 at 16:11
0

The problem is your $(ls) expands locally, rather than remotely.

Try this...

ssh -2 -4 -i $key root@$ip -- 'ls -AU /foo/bar/test_dir | wc -l > ~/file_count.txt'

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