I want to write a shell script that will add an apt repository.
I know that I can do it using sudo add-apt-repository -y <repo>.

My question is can I do it only if the repository was not added already, something like:

if repo was not added yet:
  sudo add-apt-repository -y <repo>
  sudo apt-get update


  • add-apt-repository will only add it once; the interesting part is doing the apt-get update conditionally. – Beni Cherniavsky-Paskin Aug 3 '13 at 22:11
  • Have you even actually tried adding a repository twice ? What I've done just now is add-apt-repository for a theme twice, but that resulted only into one file in /etc/apt/sources/sources.list.d .Maybe it already does the checks ? – Sergiy Kolodyazhnyy Mar 23 '16 at 18:03
  • It's been a while since I tried it but IIRC it duplicates the line in the repository's list file – Itay Mar 24 '16 at 3:55

I changed Itay's function so that it handles multiple parameters:

add_ppa() {
  for i in "$@"; do
    grep -h "^deb.*$i" /etc/apt/sources.list.d/* > /dev/null 2>&1
    if [ $? -ne 0 ]
      echo "Adding ppa:$i"
      sudo add-apt-repository -y ppa:$i
      echo "ppa:$i already exists"

To be called like this:

add_ppa webupd8team/atom xorg-edgers/ppa ubuntu-wine/ppa
  • 4
    If you want to improve another answer, please suggest an edit to it and don’t create a new answer. – David Foerster Aug 7 '16 at 8:42

I ended up writing a function to deal with ppa repositories.

add_ppa() {
  grep -h "^deb.*$1" /etc/apt/sources.list.d/* > /dev/null 2>&1
  if [ $? -ne 0 ]
    echo "Adding ppa:$1"
    sudo add-apt-repository -y ppa:$1
    return 0

  echo "ppa:$1 already exists"
  return 1

I wonder if there is some more elegant way.


Now it is possible to remove the repository prior to adding it:

sudo add-apt-repository -r $REPO
sudo add-apt-repository $REPO

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.