Bash – sudo echo “something” >> /etc/privilegedFile doesn’t work

bashpermissionsscriptingshellsudo

This is a pretty simple question, at least it seems like it should be, about sudo permissions in Linux.

There are a lot of times when I just want to append something to /etc/hosts or a similar file but end up not being able to because both > and >> are not allowed, even with root.

Is there someway to make this work without having to su or sudo su into root?

Best Answer

Use tee --append or tee -a.

echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list

Make sure to avoid quotes inside quotes.

To avoid printing data back to the console, redirect the output to /dev/null.

echo 'deb blah ... blah' | sudo tee -a /etc/apt/sources.list > /dev/null

Remember about the (-a/--append) flag! Just tee works like > and will overwrite your file. tee -a works like >> and will write at the end of the file.