Thursday 26 July 2018

linux - 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?



Answer



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


No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...