Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Possible Duplicate:
Redirecting stdout to a file you don't have write permission on

Running a command like sudo echo 'text' >> /file.txt fails with:

bash: /file.txt: Permission denied
share|improve this question

marked as duplicate by Michael Mrozek Nov 25 '10 at 23:25

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 14 down vote accepted

This doesn't work because the redirection is executed by the shell, not by the command it applies to. But your shell is not running as root, only echo 'text' is.

A common trick when you need to have root permissions to write to a file, but not to generate the data, is to use tee:

echo 'text' | sudo tee -a /file.txt

If you do need root permissions to generate the data, you can run two separate sudo commands, or run a shell inside sudo and do the redirection there (careful with the quoting).

sudo echo 'text' | sudo tee -a /file.txt
sudo sh -c 'echo "text" >>/file.txt'

When overwriting rather than appending, if you're used to your shell refusing to truncate an existing file with the > operator (set -o noclobber), remember that this protection will not apply. sudo 'echo >/etc/passwd' and sudo tee /etc/passwd will overwrite /etc/passwd.

share|improve this answer
This is definitively the better way, as this lets you easily echo complicated statements with newlines and so on. For example I didn’t manage to to the following with sudo -s, but with tee it was very easy: echo -e '#!/bin/bash\n\nexport PYTHONPATH=/usr/local/lib/python2.7/site-packages\ngtk-redshiftreal $@' | sudo tee gtk-redshift – erik Mar 8 '13 at 11:07

You are telling bash to open a file and append the output of the command sudo echo 'text' to it, which of course doesn't work since your bash runs as non-root. Interactively, I usually run sudo -s to get around this (since then the shell runs as root and can open the file). Alternatively, you can run sudo sh -c "echo 'text' >> /file.txt", which also works, but is a bit of a hassle with all the interpolation/escaping that can interfere if you have complicated expressions.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.