Two American hikers imprisoned on espionage charges in Iran were released Wednesday after days of conflicting signals, ending diplomatic skirmishing that complicated the United States’ already fraught relationship with Tehran for more than two years.

The men, Shane M. Bauer and Joshua F. Fattal, both 29, were released from the notorious Evin Prison at dusk and whisked by diplomatic convoy to a plane that took them to Oman, where they raced down the stairs of the aircraft to hug waiting family members.

The men’s odyssey through Iran’s judicial system began when, they have said, they wandered over the border from Iraq by mistake with a friend, but their case was quickly entangled with Iran’s foreign and domestic politics. In the latest chapter, the Americans’ fate became part of what analysts called a power struggle between President Mahmoud Ahmadinejad and the conservative establishment he has angered.

Mr. Ahmadinejad promised last week that the men would be freed as a humanitarian gesture “in a couple of days.” The announcement appeared calibrated to garner favorable attention for the Iranian leader before he flew to New York to attend this week’s United Nations General Assembly meeting.