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

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

Solution 1:

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.

Solution 2:

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.