Home » Questions » Computers [ Ask a new question ]

How to append to a file as sudo?

How to append to a file as sudo?

I want to do:

Asked by: Guest | Views: 384
Total answers/comments: 5
bert [Entry]

"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"
bert [Entry]

"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)"
bert [Entry]

"There may be a problem with the sudo here and the redirecting. Use a texteditor of your choice instead to add the line.

sudo nano /etc/profile

Or, you could try su instead

su
echo ‘JAVA_HOME=/usr/lib/jvm/java-6-sun’ >> /etc/profile
exit"
"There may be a problem with the sudo here and the redirecting. Use a texteditor of your choice instead to add the line.

sudo nano /etc/profile

Or, you could try su instead

su
echo ‘JAVA_HOME=/usr/lib/jvm/java-6-sun’ >> /etc/profile
exit"
bert [Entry]

"This is very simple and puts sudo first, as it is common.

sudo sed -i '$a something' /etc/config_file

$a means to append at the end of the file."
bert [Entry]

This won't work you are trying to redirect (using >>) the output of sudo. What you really want to do is redirect the output of echo. I suggest you simply use your favorite editor and add that line manually to /etc/profile. This has the additional benefit that you can check whether /etc/profile already sets JAVA_HOME.