tags:

views:

1673

answers:

5

I am new to linux, and just beginning to learn bash. I am using Ubuntu 9.04, and would like to add repositories to /etc/apt/sources.list from the command line. Basically, I would like to do this:

sudo echo "[some repository]" >> /etc/apt/sources.list

However, even when I use sudo, I get this error:

bash: /etc/apt/sources.list: Permission denied

How do I avoid this error?

+8  A: 

This does not quite belong here, but the answer is:

echo "[some repository]" | sudo tee -a /etc/apt/sources.list

The tee command is called as the superuser via sudo and the -a argument tells tee to append to the file instead of overwriting it.

Your original command failed, as the IO redirection with >> will be done as the regular user, only your echo was executed with sudo.

Calling a sudo subshell like

sudo sh -c 'echo "[some repository]" >> /etc/apt/sources.list'

works, too as pointed out by others.

lothar
Thanks for your answer--for future reference, where would this belong? Or do you mean that it doesn't belong on this site at all?
Matthew
@Matthew As it is not really programming related it probably would be a better fit on serverfault.com once it's open for everybody. Currently it's beta only (http://serverfault.com/beta-access)
lothar
A: 

One way to solve this is to do the redirection in a subshell:

sudo sh -c 'echo "[some repository]" >> /etc/apt/sources.list'

That way, the sh process is executed under sudo and therefore has the necessary privileges to open the redirected output to /etc/apt/sources.list.

Greg Hewgill
+2  A: 

The shell processes ">", "<", ">>" etc itself before launching commands. So the problem is that "sudo >> /etc/foo" tries to open /etc/foo for append before gaining privileges.

One way round this is to use sudo to launch another shell to do what you want, e.g.:

sudo sh -c 'echo "[some repository]" >> /etc/apt/sources.list'

Or alternatively:

echo "[some repository]" | sudo sh -c 'cat >> /etc/apt/sources.list'

A simpler approach may simply be to use sudo to launch an editor on the /etc/file :)

araqnid
A: 

In Karmic, you can just use the add-apt-repository command, at least for PPAs.

For example:

sudo add-apt-repository ppa:docky
Matthew
+3  A: 

Better to use a separate file in /etc/apt/sources.list.d as explained in this other answer.

Neil Mayhew
Note that the file name MUST end in .list or it will be ignored (as I just found out to my cost).
Neil Mayhew