1

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?

Jim
  • 9,750
  • 15
  • 57
  • 84

2 Answers2

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
Rastapopoulos
  • 1,569
  • 1
  • 10
  • 21
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'
David Favor
  • 423
  • 3
  • 5