Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

After reading this question, I know that I have to do

sudo sh -c 'ls -hal /root/ > /root/test.out'

to avoid the "Permission denied" error.

But when I do

ssh hostname sudo sh -c 'ls -hal /root/ > /root/test.out'

from another machine, I get

bash: /root/test.out: Permission denied

Why? And how can I get this to work?

Edit: There is the line

Defaults:<username>    !requiretty


<username> ALL= NOPASSWD: ALL

in /etc/sudoers.

I can do

ssh remote-machine 'sudo ls /'

without any problem. So I don't think it is a tty problem. Adding -t does not solve the problem.

share|improve this question
up vote 6 down vote accepted

The problem is that the quotes are interpreted and stripped by the local shell, not the remote one; you need one extra level:

ssh host sudo sh -c '"ls -hal /root/ > /root/test.out"'

The local shell will consume one level of quoting - the single quotes get "used up" here, ssh will get the arguments host, sudo, sh, -c, and "ls -hal /root/ > /root/test.out".

The remote shell consumes the next layer - the double quotes - and calls sudo with sh, -c, and ls -hal /root/ > /root/test.out.

Finally, the sh instance (running as root) is called with -c and ls -hal /root/ > /root/test.out - and parses that single argument as a normal commandline, evaluating the redirection.

To watch all of this, on the target system, try running sudo strace -f -e execve -p $(cat /var/run/

share|improve this answer
what if I want to have $1 inside the quotes? – kirill_igum Jan 9 at 1:59

Your Answer


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.