Bash "Permission denied" issue when trying to append to EOF

4

1

When trying to push a couple lines to the end of a file, I get a permission issue. I understand why I'm getting the error, but I can't think of a way to resolve it. Any help would be appreciated.

sudo cat > /etc/php5/apache2/php.ini << EOF
    # extensions
    extension=”memcached.so”
    extension=”apc.so”
EOF

onassar

Posted 2011-09-26T17:57:00.630

Reputation: 153

ls -al /etc/php5/apache2/php.ini, what's the permission settings of the file? – Jin – 2011-09-26T18:02:09.903

Answers

11

Heredoc usage, or "appending to EOF", is not the problem.

All redirections (including >) are applied before executing the actual command. In other words, your shell first tries to open /etc/php5/apache2/php.ini for writing using your account, then runs a completely useless sudo cat.

One way to get around this:

sudo bash -c "cat >> /etc/php5/apache2/php.ini" <<EOF

(You can run an interactive shell via sudo -s, or use dd or tee for writing to the file.)


On a related note, using > will overwrite the old php.ini. Use >> to append.

user1686

Posted 2011-09-26T17:57:00.630

Reputation: 283 655

Thanks grawity. I'm having issues running the above for hidden files. I get this kind of response: http://cl.ly/3K2J3Q2N1h2I3N364301

– onassar – 2011-09-26T18:58:36.543

@onassar: If you open the heredoc with "EOF", you must close it with exactly the same "EOF". Not with ".EOF" as you are currently doing. – user1686 – 2011-09-26T19:25:39.363

this is the code I'm pasting in: http://cl.ly/1w3s1p2J3U1I3C1j0q1O it's actually just being rendered improperly by my terminal.

– onassar – 2011-09-26T19:27:59.830

it seems the tabs in my code (\t character) was throwing things off. replacing those with 4 spaces did the trick. thx! – onassar – 2011-09-26T20:14:28.883

1

To expand on the answer by @grawity, showing how to use tee:

sudo tee /etc/php5/apache2/php.ini >/dev/null <<EOF
    # extensions
    extension=”memcached.so”
    extension=”apc.so”
EOF

or use the "-a" option of tee for appending instead of overwriting.

Andreas Maier

Posted 2011-09-26T17:57:00.630

Reputation: 131

0

sudo su and then you have a proper shell as root. Run the command in there, without sudo prefix. Afterwards, exit to return from the root shell.

Daniel Beck

Posted 2011-09-26T17:57:00.630

Reputation: 98 421