Append to a file owned by root

In this example I will use the sources.list file that contains a list of the repositories from which we can get packages.


  • sudo echo "#TEST REPOSITORY" >> /etc/apt/sources.list

results in a "Permission denied error". This is because the >> /etc/apt/sources.list redirection is processed by your shell before spawning sudo, so it is trying to open the file with your (ordinary) user privileges, not root privileges.

Ways around this:


  • sudo bash -c 'echo "#TEST REPOSITORY" >> /etc/apt/sources.list'

The shell spawned by sudo reads its command from the string after the -c switch, so the redirection is done in a process which is already running as root.


  • echo "#TEST REPO" | sudo tee -a /etc/apt/sources.list

The 'tee' command reads from standard input and the -a switch appends it to the file. Again, the file is opened by the process spawned by sudo, which is running as root.


  • sudo tee -a /etc/apt/sources.list <<< "#TEST REPO"

An alternative formulation of 2), using a HereString.