1

I am trying to write a script that appends a line to the /etc/hosts, which means I need sudoer privileges. However, if I run the script from the desktop it does not prompt for a password. I simply get permission denied.

Example script:

#!/bin/bash
sudo echo '131.253.13.32        www.google.com' >> /etc/hosts
dscacheutil -flushcache

A terminal pops up and says permission denied, but never actually prompts for the sudo password. Is there a way to fix this?

2
  • Does sudo work on other opparations? Commented Oct 8, 2012 at 22:15
  • It does not prompt for a password. If I do sudo ls it will run the ls command, but it doesn't run as sudo. Commented Oct 8, 2012 at 22:18

2 Answers 2

4

sudo doesn't apply to the redirection operator. You can use either echo | sudo tee -a or sudo bash -c 'echo >>':

echo 131.253.13.32 www.google.com | sudo tee -a /etc/hosts
sudo bash -c 'echo 131.253.13.32 www.google.com >> /etc/hosts'
Sign up to request clarification or add additional context in comments.

1 Comment

bash -c command not found, but the first one worked like a charm. Thank you.
1

What you are doing here is effectively:

  1. Switch to root, and run echo

  2. Switch back to yourself and try to append the output of sudo onto /etc/hosts

That doesn't work because you need to be root when you're appending to /etc/hosts, not when you're running echo.

The simplest way to do this is

sudo bash -c "sudo echo '131.253.13.32        www.google.com' >> /etc/hosts"

which will run bash itself as root. However, that's not particularly safe, since you're now invoking a shell as root, which could potentially do lots of nasty stuff (in particular, it will execute the contents of the file whose name is in the environment variable BASH_ENV, if there is one. So you might prefer to do this a bit more cautiously:

sudo env -i bash -c "sudo echo '131.253.13.32        www.google.com' >> /etc/hosts"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.