Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

up vote 6 down vote accepted

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.

share|improve this answer
    
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 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 at 17:51

The suggested solution works with pipes as well

ssh host 'some_command | some_other_command'
share|improve this answer

Even simpler, instead of:

ssh host something > file

do:

ssh host "something > file"
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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