40

I would like to have script that is doing automated migrations of websites from another be able to append Includes to the /etc/httpd/conf.d/vhosts.conf file.

However, when I try to use echo to put append a string to the end of the file I get this:

$ sudo echo "Include thing" >> /etc/httpd/conf.d/vhosts.conf
-bash: /etc/httpd/conf.d/vhosts.conf: Permission denied

and yet I can vi /etc/httpd/conf.d/vhosts.conf, add the line and :wq the file to save and close it.

What am I missing?

78

Sudo elevates the process it calls, it does not elevate any of the current shell's processing like redirection, globbing, etc.

The file redirection >> /etc/httpd/conf.d/vhosts.conf is being processed by your current shell, which is still running under your current privileges.

You could try something like this.

sudo bash -c 'echo "Include thing" >> /etc/httpd/conf.d/vhosts.conf'

Or

echo "Include thing" | sudo tee -a /etc/httpd/conf.d/vhosts.conf
| improve this answer | |
  • Would it also work to say sudo (command >> file) ? – WGroleau Jan 24 at 18:31
  • 6
    @WGroleau, no, that doesn't work; sudo needs its argument to be something it can use the execve() syscall to invoke. A shell compound command can't be invoked that way (whereas a shell with an argument that is code giving it that compound command can) -- so sudo sh -c 'command >> file' becomes execvp("sh", {"sh", "-c", "command >> file", NULL}), but without the sh -c or bash -c, there isn't really anything you can translate that command into. – Charles Duffy Jan 24 at 18:35
  • Because I hate nesting quotes, I'd just sudo bash, then type the echo command in the new shell. Or just sudo su -l. – CarlF Jan 24 at 18:56
  • @CarlF, that’s usually my approach, especially when I expect to use more than one command. – WGroleau Jan 24 at 22:38
  • @CarlF sudo -i to the rescue – vikarjramun Jan 26 at 21:43

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.