23

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?

1

3 Answers 3

15

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.

3
  • 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, 2014 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. May 7, 2014 at 17:51
  • Cross-platform note: from a Windows command prompt, single-quotes fail, but it works after replacing with double-quotes.
    – Ben Mares
    Apr 8, 2020 at 17:47
14

Even simpler, instead of:

ssh host something > file

do:

ssh host "something > file"
1
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.