17

I would like to run

something > file

on a remote system through ssh, but if I run

ssh host something > file

the redirection is executed locally as ssh etc > file

I've tried it with ' or '' or dd or with a pipe | instead, but I can't get it to work. How can this be done?

11

Try:

ssh host 'something > file'

Here's a contrived demonstration of a way to handle redirection, pipes and quotes:

ssh host date -d yesterday \| awk "'{print $1}'" \> 'file" "with\ spaces.out'

The pipe and redirection are escaped rather than being contained in an overall outer set of quotes, reducing the need to escape one level of quotes. The single quotes for the AWK command are protected by the double quotes that surround them. The filename could be protected in the same way, but here I show how the single quotes protect the double quotes and the escape.

  • thanx -- it works! – franziskus Sep 5 '10 at 15:17
  • 2
    Since ssh passes that part of its command line to the shell anyway, you don't need the sh -c part. – Jander Jan 22 '11 at 5:04
  • What if you have double quotes and single quotes in your command already? If it's not too far off-topic I'm sure others would want to know how... – labyrinth May 7 '14 at 17:11
  • 1
    @labyrinth: I added an example to give you some ideas. Note that the local shell consumes the outermost set(s) of quotes and the remote shell consumes the next level. In other words, for example, AWK doesn't see any quotes in its arguments as shown, but its $1 is protected from being seen by the shell as a shell variable. But it wouldn't be if the order of the quotes were opposite. – Dennis Williamson May 7 '14 at 17:51
10

Even simpler, instead of:

ssh host something > file

do:

ssh host "something > file"
  • this should be the accepted answer because it came by earlier than the other one. – Blauhirn Aug 15 '18 at 20:55
  • Yeah the accepted answer in 2010 was not so good. It was changed in 2014 probably to match this answer. unix.stackexchange.com/revisions/1631/1 – Amala Aug 16 '18 at 1:01
3

The suggested solution works with pipes as well

ssh host 'some_command | some_other_command'

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.