1

How might one copy the newest text file from a particular directory on a remote server to his local machine?

On the server itself I can do the following:

$ cat `cd /home/user/dir ; readlink -f $(ls -t | head -1)` > ~/newest.txt

This puts the content of the newest file into ~/newest.txt. However, I cannot run this over SSH because the local system tries to interpret the tick marks and $(*) commands. Id est, this does not work:

$ ssh me@server.com "cat `cd /home/user/dir ; readlink -f $(ls -t | head -1)`" > ~/newest.txt
bash: cd: /home/user/dir: No such file or directory
Connection to server.com closed.

Obviously, /home/user/dir does not exist on my local machine. I tried using SSH with the -t flag as well, this did not help. How can I get the ticks and $() to be parsed on the remote machine, not on my local machine?

As an aside, somebody smarter than me once declared that the output of ls shall not be parsed. We can safely assume for purposes of this question that the filenames contain only printable ASCII characters. However, answers which address the general case would be great as well as I do want to learn, not just get by this once.

  • 1
    Hi! First, please use code tag around your ssh commands starting from $ until the end of the line because they are printed wrong now - backticks are not displayed. I tried to edit your post but a single edit must be more than 8 characters and I couldn't do it. – Arkadiusz Drabczyk Aug 24 '14 at 13:37
  • @ArkadiuszDrabczyk: Thanks, sorry about that! – dotancohen Aug 24 '14 at 13:43
7

You need to use single quotes instead of double quotes to prevent shell expansion before your command is passed to a remote server.

BTW, $( are now preferred over ` in command substitution. Unless you use shell that only supports ` consider using $( in command substitution. See here for more details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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