US Army Sergeant Bowe Bergdahl, who was captured and held by the Taliban for five years after walking away from his post in Afghanistan, has pleaded guilty to desertion and endangering his comrades – charges that could put him behind bars for the rest of his life.

“I understand that leaving was against the law,” said Bergdahl, who admitted guilt without striking a deal with prosecutors, meaning his punishment will be up to a military judge when he is sentenced later this month.

The guilty plea brings the highly politicised saga closer to an end eight years after Bergdahl vanished.

Army Sergeant Bowe Bergdahl, right, arrives for a motions hearing(Andrew Craft/AP)

President Barack Obama brought him home in 2014 in a swap for five Taliban prisoners at Guantanamo Bay, saying the US does not leave its service members on the battlefield.

Republicans roundly criticised Mr Obama and Donald Trump went further while campaigning for president, repeatedly calling Bergdahl a “dirty, rotten traitor” who deserved to be executed by firing squad or thrown out of a plane without a parachute.

Bergdahl, 31, has said he walked away from his remote post in 2009 with the intention of reaching other commanders and drawing attention to what he saw as problems with his unit.

He told the judge, Colonel Jeffrey Nance, that he now understands that his actions prompted an intensive search during which some of his comrades were seriously wounded.

“At the time, I had no intention of causing search-and-recovery operations,” he said in court. “I believed they would notice me missing, but I didn’t believe they would have reason to search for one private.”

Bergdahl, who received a promotion due all missing-in-action soldiers while he was in captivity, pleaded guilty to desertion and misbehaviour before the enemy, a relatively rare charge brought against him for endangering comrades sent to find him.

The misbehaviour charge carries a maximum penalty of life in prison, the desertion charge up to five years.

Bergdahl’s answers to the judge’s questions represented some of his most extensive public comments yet.

He told the judge he tried to escape from his captors 12 to 15 times with varying degrees of success. Once, he was on his own for about a week – hoping US drones would spot him – before he was recaptured. He said he also tried to escape on his first day in captivity.

“As I started running there came shouts, and I was tackled by people. That didn’t go so well,” said Bergdahl.

He also reflected on what he thought were questionable tactics by US soldiers and their Afghan allies in guarding a remote crossroads that could be bypassed by the Taliban on other routes. He said the set-up “seemed to be a bit of a joke”.

Pressed by the judge about his actions, Bergdahl acknowledged endangering his fellow service members.

“I left my platoon in a battlefield … a situation that could easily turn into a life-or-death situation,” he said.