How to append to a file as sudo?

I want to do:

echo "something" >> /etc/config_file

But, since only the root user has write permission to this file, I can't do that. But the following also doesn't work.

sudo echo "something" >> /etc/config_file

Is there a way to append to a file in that situation without having to first open it with a sudo'd editor and then appending the new content by hand?


Use tee -a (or tee --append) with sudo

tee - read from standard input and write to standard output and files
[...]
   -a, --append
      append to the given FILEs, do not overwrite
[...]

So your command becomes

echo "something" | sudo tee -a /etc/config_file

The advantages of tee over executing Bash with administrative permissions are

  • You do not execute Bash with administrative permissions
  • Only the 'write to file' part runs with advanced permissions
  • Quoting of a complex command is much easier

The redirection is executed in the current shell. In order to do the redirection with elevated privileges, you must run the shell itself with elevated privileges:

sudo bash -c "somecommand >> somefile"