How to append to a file as sudo?
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"
Have sudo spawn a sub-shell:
sudo sh -c "echo 'JAVA_HOME=/usr/lib/jvm/java-6-sun' >> /etc/profile"
In this example, sudo runs "sh" with the rest as arguments.
(this is shown as an example in the sudo man page)