How can I append text to /etc/apt/sources.list from the command line?

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 :)


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.

Tags:

Bash