Army Sgt. Bowe Bergdahl, who walked off his post in Afghanistan in 2009 and was held in captivity for five years by the Taliban, pleaded guilty to desertion and misbehavior before the enemy on Monday, saying “I understand leaving was against the law.”

“I left my observation post on my own,” Bergdahl told Judge Col. Jeffrey Nance at his hearing at Fort Bragg in North Carolina. “I understand leaving was against the law.”

“At the time, I had no intention of causing search and recovery operations,” Bergdahl said, adding that he now acknowledges that his disappearance prompted a manhunt by his fellow service members.

The misbehavior charge, which says he endangered his comrades by leaving his post, carries a maximum penalty of life in prison, while the desertion charge is punishable by up to five years.

Bergdahl, who is assigned to desk duty at a Texas base, is scheduled to be sentenced on Oct. 23.

During pretrial hearings in June, a judge allowed prosecutors to present evidence of the serious wounds troops suffered searching for Bergdahl after left his remote post in June 2009.

Now-retired Navy SEAL James Hatch told a judge in June how he was shot in the leg, shattering his femur, by an AK-47 round while looking for Bergdahl with other special operation troops.

After 18 surgeries, Hatch still walks with a limp.

Army Sgt. 1st Class Mark Allen was shot in the head during the search and lost part of his brain. He is paralyzed and partially mute because of the wound.

The judge also dismissed claims from Bergdahl’s defense team that comments made by then-candidate Donald Trump, who called him a “no-good deserter” who should be executed during the campaign, would unfairly sway the case.

While Trump’s remarks we “disturbing and disappointing,” the judge said they were made “to enflame the passions of the voting populace” and could not amount to “unlawful command influence” because Trump was not yet president.

Bergdahl, who is from Idaho, told military officials after his release that he left his post so that he could go to another larger base around 18 miles away to report problems with his unit.

He was freed in 2014 in exchange for five Taliban prisoners who were being held in Guantanamo Bay.

In an interview taped a year ago that aired on ABC on Monday, Bergdahl rejected allegations that he sympathized with his Taliban captors and even took up arms against his former comrades.

“You know, it’s just insulting frankly,” Bergdahl said. “It’s very insulting, the idea that they would think I did that.”

With Wires