4

I ran this code:

sudo cat <<EOF | sudo sed -e "s,%,$,g" >/etc/init.d/dropbox
  echo "Hello World"
EOF

But even though, I get "permission denied", cause you have to be root to make changes in the /etc/init.d directory. And somehow, my command above doesn't work.

Is there a way to solve this?

8k_of_power
  • 633
  • 2
  • 6
  • 10

3 Answers3

7

The redirection to a file is handled by bash. It does therefore not inherit permissions granted by sudo.

Use sudo tee for writing to a file as root.

Try this:

cat | sed -e 's,%,$,g' | sudo tee /etc/init.d/dropbox << EOF
  echo "Hello World"
EOF

Notice that $, inside double quotes might be interpreted.

Benoit
  • 6,993
  • 4
  • 23
  • 31
5

You could grant yourself persistent su-rights with
# sudo -s

then your command (do not need to sudo anymore) and exit with
# exit

EDIT:
I assume you're asking Ubuntu-related because your question is tagged with that. In other distribution like Suse you'll have the ability to use
# su
instead of # sudo -s

MOnsDaR
  • 146
  • 4
0

This part: sudo sed -e "s,%,$,g" >/etc/init.d/dropbox cen be viewed as this:

sudo somecommand --put the result of the sudo command into--> /etc/init.d/dropbox

In the same way as this:

ls somedirectory > filename
ls somedirectory --put the result of the ls command into--> filename

This means that the file writing will be done as your current user, not as root.

You can solve it by using tee as Benoit shows in his answer.

Emil Vikström
  • 419
  • 3
  • 19