[Tex/LaTex] natbib + BibTeX: suppress url if doi is available

bibtexconditionalsdoinatbiburls

I am using natbib (+ BibTeX). Some entries in my bibliography file (.bib) have the field doi, some have url and some have both.
I would like to edit the bibliography style file (.bst) so that, if doi is available, url is suppressed.

At the moment, the .bst file has the functions:

FUNCTION {format.doi}
{ doi empty$
    { "" }
    {
      new.block
      "\doi{" doi * "}" *
    }
  if$
}

FUNCTION {format.url}
{
  url
  duplicate$ empty$
    { pop$ "" }
    { "\urlprefix\url{" swap$ * "}" * }
  if$
}

[I was looking for a solution to this problem and found some similar questions and answers. However, they didn't address this specific case. After searching and trying, I could solve it. I present the solution as a reply for my own question to document it.]

Best Answer

You can achieve it by testing if doi is empty inside the function format.url. Replace your format.url by the following:

FUNCTION {format.url}
{
  doi empty$
    {    
      url
      duplicate$ empty$
        { pop$ "" }
        { "\urlprefix\url{" swap$ * "}" * }
      if$
    }
    { "" }
  if$
}